2

I have a vector < vector < Point> > X and want to copy all the elements in it into a vector < Point > Y (and in the same order if is possible) I tried something like (in a for cycle):

Y.push_back(i) = X.at(i).at(i);

but obviously it doesn't work...

I also find this (on stackoverflow) but it doesn't work for me as well...

for (std::vector<std::vector<Point> >::iterator it = X.begin(), itEnd = X.end(); it != itEnd; ++it)
    Y.push_back((*it));

but the compiler tells me that "there isn't an instance of function in overload" (and honestly I don't even know what does it mean).

Fox32
  • 13,126
  • 9
  • 50
  • 71
Marco Maisto
  • 91
  • 2
  • 11

2 Answers2

5
for(vector<vector<Point> >::iterator it = X.begin(); it != X.end(); ++it)
     Y.insert(Y.end(), it->begin(), it->end());

If you know the size of the resulting vector, you could call Y.reserve(finalYSize) before the loop.

Fox32
  • 13,126
  • 9
  • 50
  • 71
  • 2
    For people not using c++11 add a space between `>>`. i.e: `for(vector< vector >::iterator it = X.begin(); it != X.end(); ++it)` – Charles Beattie Apr 03 '12 at 09:21
  • Thanks, forgot about it... C++11 ftw! – Fox32 Apr 03 '12 at 09:23
  • a question, as well we are here :P why it would be important (i think) to do the .reserve and give a size to the vector?wich is the difference if i don't do it? (and in the specific case, i wouldn't do it, because i don't know exactly the size of the resulting vector). thx again. – Marco Maisto Apr 03 '12 at 09:36
  • In C++11, you should obviously use the much more readable range-based for-loop `for (auto& subvct: X) Y.insert(Y.end(), subvct.begin(), subvct.end());`, which is completely equivalent. – leftaroundabout Apr 03 '12 at 09:48
0
 Y.push_back(i) = X.at(i).at(i);

This takes element i from the vector i. If you want to copy all the elements:

 vector<vector<Point> > X;
 vector<Point> Y;
 //....
 for ( int i = 0 ; i < X.size() ; i++ )
    for ( int j = 0 ; j < X[i].size() ; j++ )
       Y.push_back(X[i][j]);

Edit: As per the comments and the other answer, the more C++-ish way of doing it is found also in this question - What is the best way to concatenate two vectors?

Community
  • 1
  • 1
Luchian Grigore
  • 253,575
  • 64
  • 457
  • 625
  • I would suggest using `insert` instead of the inner for loop. – Andreas Brinck Apr 03 '12 at 09:10
  • This is correct. Just some additional readings http://stackoverflow.com/questions/3177241/best-way-to-concatenate-two-vectors http://stackoverflow.com/questions/201718/how-to-concat-two-stl-vectors – RedX Apr 03 '12 at 09:14
  • really really really thanks! :) also this method works perfectly :) – Marco Maisto Apr 03 '12 at 09:26