How to Remove Last Element from Vector in C++?
Last Updated :
05 Feb, 2024
In C++, vectors are dynamic arrays that provide flexibility and convenience over traditional arrays with additional features such as automatic resizing, ease of insertion and deletion of elements, etc. In this article, we’ll learn how to remove the last element from a vector in C++.
For Example,
Input:
myVector = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output:
myVector = {1, 2, 3, 4, 5, 6, 7, 8, 9}
Remove Last Element from a std::vector in C++
The vector containers have the std::vector::pop_back() function which provides a simple and efficient way to remove the last element from a vector in C++ STL. It is a member function of the std::vector class and can be used as shown
Syntax of std::vector::pop_back()
vector<int> myVector = {1, 2, 3, 4, 5};
myVector.pop_back();
C++ Program to Remove Last Element from Vector in C++
C++
#include <iostream>
#include <vector>
using namespace std;
int main()
{
vector< int > Rollno = { 1, 2, 3, 4, 5 };
cout << "Before pop_back(): " ;
for ( int num : Rollno) {
cout << num << " " ;
}
cout << endl;
Rollno.pop_back();
cout << "After pop_back(): " ;
for ( int num : Rollno) {
cout << num << " " ;
}
cout << endl;
return 0;
}
|
Output
Before pop_back(): 1 2 3 4 5
After pop_back(): 1 2 3 4
Time Complexity: O(1)
Auxilary Space : O(1)
We can also use iterators with std:vector::erase() function to remove the last element but using pop_back() is the simplest and most efficient.
Share your thoughts in the comments
Please Login to comment...