Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ pushing elements of a vector of vectors into a vector

Tags:

c++

vector

I'm just wondering whether there is a simple, quick way to insert the elements of a vector of vectors inside a vector.

For example:

std::vector<std::vector<double> > vals
{

    {1, 2, 3, 4, 5, 6},
    {1, 2, 3, 4, 5, 6}
};
std::vector<double> myvector;

so myvector would then contain: 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6

I've tried using insert and push_back but had no luck.

Edit:

I have used:

myvector.insert(vals.begin(), vals.end()); - No matching member function to call to 'insert'

like image 244
Phorce Avatar asked Dec 14 '25 12:12

Phorce


2 Answers

Try

// c++11
for(auto && v : vals){
  myvector.insert(myvector.end(), v.begin(), v.end());
}

// non c++11
for(std::vector<std::vector<double> >::const_iterator it = vals.begin(), end = vals.end(); it != end; ++it){
  myvector.insert(myvector.end(), it->begin(), it->end());
}
like image 200
RedX Avatar answered Dec 17 '25 01:12

RedX


Depending on how your vector of vectors is built in the first place, there may be a more efficient way to approach this.

If your sub-vectors are all the same length (as appears to be the case from the code example), then the best thing may be to view myvector as a 2D array and build directly into this buffer.

If the sub-vector lengths can vary, but the code that builds your vector of vectors only ever actually adds stuff at the end, then you can use something like the 'collapsed vector vector' class I describe here to build this data, instead of a vector of vectors. (And after that, again, your data is already in the kind of contiguous buffer you are looking for.)

Either way, if performance or memory footprint are important here then avoiding the vector of vector construct can eliminate a lot of buffer manipulation overhead, and work out as quite a significant optimisation.

like image 40
Thomas Young Avatar answered Dec 17 '25 01:12

Thomas Young



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!