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:


std::vector:
* Concatenating Vectors

Table Of Contents
8 Arrays
11 Loops
23 std::vector
39 Streams
51 Unions
56 Lambdas
60 SFINAE
62 RAII
67 Sorting
84 RTTI
87 Scopes
104 Profiling
107 Recursion
117 Iteration
125 Alignment
134 Semaphore
136 Debugging
139 Mutexes
142 decltype