Vector pop_back() in C++ with examples

This tutorial will discuss how the method vector:: pop_back() in C++ is going to work.

Vectors in C++ STL are similar to dynamic arrays which have a variable size. The storage in vectors is maintained by containers.

In a vector, the elements are stored contiguously and we can access them using iterators.

Data elements are inserted at the end. As we need to resize the vector for inserting new elements it takes differential time.

We can also remove elements in a vector from the end and it takes a constant amount of time as there will be no resizing.

vector::pop_back() demonstration:

pop_back() function will remove the last element from the vector.

Here the element is removed and the vector size is reduced by 1.

Syntax:

vectorname.pop_back()

Here no parameters are passed.

Example:

Input: v1={1,2,3,4,5,6}

v1.pop_back();

Output: v1={1,2,3,4,5}

C++ Code: Vector pop_back()

#include <bits/stdc++.h>
using namespace std;

int main()
{
  //declare the vector  
  vector<int>v1={1,2,3,4,5,6};
  //pop the last element 
  v1.pop_back();
  //printing after poping 
  cout<<"The vector elements after poping the last element: "; 
  //"it" is an iterator to iterate the vector
  for(auto it=v1.begin();it!=v1.end();it++){
      cout<<*it<<" ";
  }    
    return 0;
}

 

Output:

The vector elements after poping the last element: 1 2 3 4 5

Also read: How to return a vector in C++

Leave a Reply

Your email address will not be published.