views:

4633

answers:

4

how to concat two stl vectors?

+5  A: 

I would use the insert function Something like:

vector<int> a, b;
//fill with data
b.insert(b.end(), a.begin(), a.end());
Tom Ritter
Change a.front() to a.begin().
smink
thanks, this works. note to stl: you are too verbose!
+18  A: 
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
Robert Gamble
I'd only add code to first get the number of elements each vector holds, and set vector1 to be the one holding the greatest. Should you do otherwise you're doing a lot of unnecessary copying.
Joe Pineda
+3  A: 
std::vector<int> first;
std::vector<int> second;

first.insert(first.end(), second.begin(), second.end());
James Curran
+8  A: 

Or you could use:

std::copy(source.begin(), source.end(), std::back_inserter(destination));

This pattern is useful if the two vectors don't contain exactly the same type of thing, because you can use something instead of std::back_inserter to convert from one type to the other.

Roger Lipscombe
the copy method is a not such a good way. It will call push_back multiple time which means that if a lot of elements have to be inserted this could mean multiple reallocations. it is better to use insert as the vector implementation could do some optimization to avoid reallocations. it could reserve memory before starting copying
Yogesh Arora
@Yogesh: granted, but there's nothing stopping you calling `reserve` first. The reason `std::copy` is sometimes useful is if you want to use something other than `back_inserter`.
Roger Lipscombe
@Roger totally agree with that.
Yogesh Arora