Appending a vector to a vector

sub picture sub · Mar 31, 2010 · Viewed 615.7k times · Source

Assuming I have 2 standard 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 vector<int>::push_back(), though I wouldn't like to do that!

Answer

Andreas Brinck picture Andreas Brinck · Mar 31, 2010
a.insert(a.end(), b.begin(), b.end());

or

a.insert(std::end(a), std::begin(b), std::end(b));

The second variant is a more generically applicable solution, as b could also be an array. However, it requires C++11. If you want to work with user-defined types, use ADL:

using std::begin, std::end;
a.insert(end(a), begin(b), end(b));