tags:

views:

445

answers:

2

Assuming I have 2 STL vectors:

vector<int> a;
vector<int> b;

Let's also say the both have around 30 elements.

  • How do I add the vector b to the end of vector a?

The dirty way would be iterating through b and adding each element via push_back, though I wouldn't like to do that!

+17  A: 
a.insert(a.end(), b.begin(), b.end());
Andreas Brinck
@sbi: I had a nasty bug I just found in my code, works now, thanks.
sub
+3  A: 
std::copy (b.begin(), b.end(), std::back_inserter(a));
skwllsp
Note that this is likely to be less efficient than using `std::vector<>::insert()`, because `std::copy()` can't reserve enough space before-hand (it doesn't have access to the vector itself, only to an iterator which has), while `std::vector<>::insert()`, being a member function, can. (It needs to figure out that the iterators to read from are random-access iterators in order to pre-calculate the sequence's length, but it would be a weak implementation which wouldn't do this.)
sbi
True in practice, but in theory the `std::` implementor can make it work. They can use non-standard extensions internally.
MSalters
@MSalter: I know that an implementation _could_ do this. This is why I wrote it is "likely to be less efficient". In theory, an implementer could add a private interface to `std::back_inserter_iterator<std::vector<T>>` to allow an implementation of `std::copy()` to recognize it and use this private interface to get hold of the `std::vector` and call `reserve()` on it. In practice, however, it's unlikely any implementer jumps through all these hoops to optimize such a corner case.
sbi