Append a value to end of a std::vector in C++
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> int main() { std::vector<int> values = {3, 4, 6, 7}; int item = 8; values.push_back(item); for (int &i: values) { std::cout << i << ' '; } return 0; } |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> int main() { std::vector<int> values = {3, 4, 6, 7}; int item = 8; values.insert(values.end(), item); for (int &i: values) { std::cout << i << ' '; } return 0; } |
Output:
3 4 6 7 8
The std::vector::insert function allows inserting the multiple elements before the specified position, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include <iostream> #include <vector> int main() { std::vector<int> values = {3, 4, 6, 7}; std::vector<int> items = {8, 9}; values.insert(values.end(), items.begin(), items.end()); for (int &i: values) { std::cout << i << ' '; } return 0; } |
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> values = {3, 4, 6, 7}; std::vector<int> items = {8, 9}; std::copy(items.begin(), items.end(), std::back_inserter(values)); for (int &i: values) { std::cout << i << ' '; } return 0; } |
Output:
3 4 6 7 8 9
That’s all about appending a value to the end of a vector in C++.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)