This post will discuss how to append a value to the end of a vector in C++.

1. Using std::vector::push_back

The standard solution to add an element at the end of the vector is using the std::vector::push_back member function. A typical invocation for this method would look like this:

Download  Run Code

Output:

3 4 6 7 8

2. Using std::vector::insert

Alternatively, we can use the std::vector::insert member function, which inserts the specified element before the specified position. It can be used as follows:

Download  Run Code

Output:

3 4 6 7 8

 
The std::vector::insert function allows inserting the multiple elements before the specified position, as shown below:

Download  Run Code

Output:

3 4 6 7 8 9

3. Using std::copy

Another option is to use the std::copy algorithm to append values to the end of a vector, as shown below. Note that std::back_inserter is used for allocating space for the new element.

Download  Run Code

Output:

3 4 6 7 8 9

That’s all about appending a value to the end of a vector in C++.