This post will discuss how to join or concatenate two vectors in C++. The resulting vector will contain all the elements of the first vector, followed by all elements of the second vector in the same order.

For example, consider the following vectors x and y, whose concatenation results in vector v.


Input:
x = { 1, 2, 3 };
y = { 4, 5 };

Output:

v = { 1, 2, 3, 4, 5 };

1. Using vector::insert function

The simplest solution is to use a copy constructor to initialize the target vector with the copy of all the first vector elements. Then, call the vector::insert function to copy all elements of the second vector. We can also use only vector::insert to copy elements of both vectors into the destination vector.

Download  Run Code

2. Using std::copy function

There are many ways to use the std::copy algorithm to concatenate the vectors, as shown below. Please note that std::back_inserter is used to allocate space for the new element in the new vector. Alternately, we can allocate the space beforehand and use normal input iterators.

Download  Run Code

3. Using std::move function

Another efficient solution is to use std::move that actually moves the objects, unlike std::copy, which copies them. We can use it in the same way as std::copy. Please note that the original container elements are left in an unspecified but valid state after std::move is called.

Download  Run Code

4. Using std::set_union function

Another approach might be to use std::union that does the union of two sorted ranges. Please note that this might not preserve the original order of elements in both vectors.

Download  Run Code

That’s all about concatenating two vectors in C++.