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.

Download  Run Code

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:

Download  Run Code

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.

Download  Run Code

Output:

1 2 3

That’s all about removing an element from the end of a vector in C++.