Open In App

How to Remove Last Element from Vector in C++?

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ Program to Demonstrate how to remove the last element
// from the vector
#include <iostream>
#include <vector>
  
using namespace std;
  
int main()
{
    // Create a vector of integers
    vector<int> Rollno = { 1, 2, 3, 4, 5 };
  
    // Display the elements before pop_back()
    cout << "Before pop_back(): ";
    for (int num : Rollno) {
        cout << num << " ";
    }
    cout << endl;
  
    // Remove the last element using pop_back()
    Rollno.pop_back();
  
    // Display the elements after 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.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads