Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vector of vectors to 1D array

I was wondering if there is a clever way of presenting the information in a vector as a 1D array. Example: Let's create a vector of vectors of 5x3 int elements

vector< vector<int>> iVector;
ivector.resize( 5 );
for(i = 0; i < 5; i++){
    iVector[i].resize(3);
}

But now I want this structure to be converted into a 1D array:

int* myArray = new int[5*3];

So I could access each element which I want as follows:

for (i =0;i < 5; i++)
  for(j =0; j< 3; j++)
      myArray[i*3+j] = ...

I know I could just copy the vector to the array element by element, but I was wondering if there is a method that directly addresses the vector to array conversion. I also know that the vector can me addressed as iVector[i][j] , but unfortunately it needs to be an array as it will be sent to a GPU and GPUs dont understand vectors.

like image 230
Manolete Avatar asked Oct 18 '12 11:10

Manolete


1 Answers

Just use std::copy 5 times.

int* ptrArray = myArray;
for (i =0;i < 5; i++) {
  std::copy(iVector[i].begin(), iVector[i].end(), ptrArray);
  ptrArray += iVector[i].size();
}
like image 151
PiotrNycz Avatar answered Sep 28 '22 07:09

PiotrNycz