Concatenating Vectors

suggest change

One std::vector can be append to another by using the member function insert():

std::vector<int> a = {0, 1, 2, 3, 4};
std::vector<int> b = {5, 6, 7, 8, 9};

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

However, this solution fails if you try to append a vector to itself, because the standard specifies that iterators given to insert() must not be from the same range as the receiver object’s elements.

Instead of using the vector’s member functions, the functions std::begin() and std::end() can be used:

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

This is a more general solution, for example, because b can also be an array. However, also this solution doesn’t allow you to append a vector to itself.

If the order of the elements in the receiving vector doesn’t matter, considering the number of elements in each vector can avoid unnecessary copy operations:

if (b.size() < a.size()) {
  a.insert(a.end(), b.begin(), b.end());
} else {
  b.insert(b.end(), a.begin(), a.end());
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents