Remove an element from end of a vector in C++
This post will discuss how to remove an element from the end of a vector in C++. The solution should effectively reduce the vector size by one.
1. Using std::vector::erase
The standard solution to remove an element from a vector is with the std::vector::erase function. It takes an iterator to the position where the element needs to be deleted. To delete an element at the end of a vector, pass an iterator pointing to the last element in the vector.
Here’s what the code would look like. Note that std::vector::end does not return an iterator to the last element of the vector, but one past the last element.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4}; vec.erase(vec.end() - 1); for (int &i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3
2. Using std::vector::pop_back
To specifically remove the last element from a vector, consider using the std::vector::pop_back function. It can be invoked as follows:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4}; vec.pop_back(); for (int &i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3
3. Using std::vector::resize
The std::vector::resize function resizes the vector to contain the supplied number of elements. If the size is less than the vector’s size, all elements beyond the specified size are removed and destroyed. This can be used to remove elements from the end of a vector as follows, but it doesn’t make the context clear.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include <iostream> #include <vector> int main() { std::vector<int> vec = {1, 2, 3, 4}; vec.resize(vec.size() - 1); for (int &i: vec) { std::cout << i << ' '; } return 0; } |
Output:
1 2 3
That’s all about removing an element from 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 :)