push_back() and pop_back() function in C++ STL

In this CPP tutorial, we are going to discuss push_back() and pop_back() function used to push and pop element in vectors in STL.

push_back() and pop_back() function in C++

Let’s learn what is STL if you don’t know

What is STL?

The C++ Standard Template Library ( STL )  developed by Stepanov and Lee is a software library of container classes, algorithm, and iterators. It is a set of template classes. The STL works through the use of templates. The time complexity of templates used in STL are mostly best that’s why it is used by coders in competitive programming a lot.

STL has four components:-

  1. Containers
  2. Functions
  3. Iterators
  4. Algorithm

What is Vector in C++



Vectors are the same as dynamic arrays. Their storage is handled automatically. It has the ability to resize itself automatically when an element is inserted or deleted.

Syntax :- vector< data_type>vector_name ;

Example :- vector < int > v;

What push_back() function do in STL ?

push_back() function push new elements into vector from back and increases the size of the container by 1.

   Syntax :- vector_name.push_back(element)

element to be pushed into vector is passed as an argument and size of container automatically increases by 1.

Example:- We have to push a value 4 in a vector of integers with name v.

 v.push_back(4);

What pop_back() function do in STL ?

pop_back() function removes an element from back of vector and reduces its size automatically by 1.

Syntax:- vector_name.pop_back() 

nothing is passed in the parameter.

Example:- Suppose, we have a vector v consists of elements 1,2,3,4 we have to remove 4 from the vector.

   v.pop_back();

C++ code implementation of push_back() and pop_back() function

#include<bits/stdc++.h>
 
using namespace std;
 
  int main()
 
{
     vector<int>v;          // vector declaration
     
        v.push_back(1);     // entering element 1 in the vector
        
        v.push_back(2);     // entering element 2 in the vector
        
        v.push_back(3);     // entering element 3 in the vector
        
        v.pop_back();        // removing last element i.e. 3 from the vector
        
        for( auto it=v.begin();it!=v.end();it++)
          
             cout<<*it<<" ";
 }

OUTPUT

1 2

Here, in vector v value 1, 2 and 3 is first inserted using push_back() function , then one pop_back() function is called which removes last  value 3 from vector. So, finally output is 1 2.

You may also interested in,

Leave a Reply

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