Remove Last Element from Vector in C++

Learn about how to remove last element from Vector in C++.

C++ provides a very useful data structure called vectors. These objects are similar to arrays in storing similar elements under a common name. However, they have a very useful additional feature. Vectors are dynamic in C++, which means that we can remove and add elements as we go.

To work with vectors we need to add the vector header file at the start of the program. There are a lot of ways to remove elements from vectors in C++. We will discuss how to remove last element from vector in C++.

Ways to Remove Last Element from Vector in C++

Let us now discuss the different methods to remove last element from vector in C++.

Using the vector::pop_back() function to remove last element from vector in C++

The pop_back() method is defined in the vector header file and is used to remove last element from vector in C++. We can use this function directly with the required vector.

For example,

Output:

7
1
2
5

In the above example, we created a vector v and removed the last element from this vector using the pop_back() function. We display the vector using a for loop afterward.

Using the vector::resize() Function to Remove Last Element from Vector in C++

The resize() function can be used to alter the size of any given vector. We can specify the required size within the function. When we reduce the size of a vector, all the extra elements get automatically removed.

To remove last element from vector in C++, we need to specify the new size after subtracting one from the total length of the vector. We can use the size() function to return the length of a vector.

See the code below.

Output:

7
1
2
5

Using the vector::rrase() Function to Remove Last Element from Vector in C++

The vector::erase() function is used commonly to remove an element in a given vector. We can specify the iterator that points to the position of the element which we want to delete.

To remove last element from vector in C++, we can use this function. We can use the end() function to return an iterator pointing to one past the last element. We can subtract one from this to point to the final element.

For example,

Output:

7
1
2
5

Conclusion

To wrap up, we discussed several methods to remove last element from vector in C++. The first method is very straightforward. We directly use the pop_back() function to remove last element from vector in C++.

We can also alter the size of the vector using the resize() function and reduce its length by one, which results in removing the last element. The erase() function also removes elements from a vector. We specify an iterator pointing to the last element to remove it using this function.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *