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
2008-10-14 15:48:15
Change a.front() to a.begin().
smink
2008-10-14 15:52:16
thanks, this works. note to stl: you are too verbose!
2008-10-14 15:52:56
+18
A:
vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
Robert Gamble
2008-10-14 15:48:28
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
2008-10-14 16:11:42
+3
A:
std::vector<int> first;
std::vector<int> second;
first.insert(first.end(), second.begin(), second.end());
James Curran
2008-10-14 15:48:37
+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
2008-10-14 16:20:34
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
2010-03-22 13:16:31
@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
2010-03-22 18:36:29