C++ vector::pop_back() usage with example

In C++, the standard library provides us with vectors, which are dynamic arrays. It consists of multiple homogeneous objects, which can be accessed by their position in the vector. It is automatically resized (if needed). The vector::pop_back() is a C++ Standard Library function which removes an element from the end of a vector. It effectively reduces the size of a vector by 1.

Syntax:

vector_name.pop_back();

Parameters: The vector::pop_back() function does not accept any parameter
Return value: none

Example of vector::pop_back() function

#include <iostream>
#include <vector>
using namespace std;

int main ()
{
  vector<int> vec;

  for(int i=1;i<=5;i++)
    vec.push_back(i);

  cout<<"Vector before popping: ";
  for(vector<int>::iterator it=vec.begin();it!=vec.end();++it)
    cout<<*it<<"  ";
  cout<<endl;

  vec.pop_back();

  cout<<"Vector after popping: ";
  for(vector<int>::iterator it=vec.begin();it!=vec.end();++it)
    cout<<*it<<"  ";
}

Output:

Vector before popping: 1  2  3  4  5
Vector after popping: 1  2  3  4

This article is written by

Please comment below, if you have any doubts or find any error in the above article.

Leave a Comment

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

Scroll to Top