0

I have searched for a good answer to this question but have been unable to find one. I found the following question, but it does not answer the question below (this question relates to converting a 2D array to a vector, not just a 1D array):

I have the following function that is passed a 2D array as a double pointer and the dimensions of the first and second indices in the array:

std::vector<std::vector<float>> ConvertToVector(const float **a_data,
  const int a_d1, const int a_d2)

I want to convert a_data to a 2D vector and return the vector. My only solution so far is to step through each of the elements in the first dimension of the array and push back each element as follows:

std::vector<std::vector<float>> dataVec;
for (int i=0; i<a_d1; i++)
{
  std::vector<float> v(a_data[i], a_data[i]+a_d2);
  dataVec.push_back(v);
}
return dataVec;

Is there a simpler/more elegant solution than this?

Community
  • 1
  • 1
Burrow
  • 111
  • 3
  • Yeah, I read the answer to that question but it did not answer my question about how to convert a 2D array to a vector. Is there a simple way to convert a 2D array to a vector? – Burrow Nov 21 '16 at 21:10
  • The only other solution I can think of would be memcpys and I wouldn't call those 'elegant'. Pointer magic can take you from vectors to float*, but not the other way around. I assume there is a good reason you can't just load a_data as vectors directly and need it to be vectors instead of pointers. – mjr Nov 21 '16 at 21:12
  • 1
    *this question relates to converting a 2D array to a vector, not just a 1D array* — A 2D array is made up of 1D arrays, so implement the 1D approach in a loop. – Jonny Henly Nov 21 '16 at 21:18
  • @JonnyHenly I have implemented the 1D approach in a loop as shown in the code in the original question. Is there a better way than to just use a loop or should I just stick with the loop? – Burrow Nov 21 '16 at 21:22
  • @Burrow I'd stick with the loop. – Jonny Henly Nov 21 '16 at 21:33
  • `emplace_back()` is more elegant than `vector()`+`push_back()`. And I guess you meant to write `i+=d1` in the loop control. – Toby Speight Nov 23 '16 at 16:09

0 Answers0