Delete last element from a set in C++

In this tutorial, we will learn how to delete the last element from a Set in C++.

First, let me introduce to you what are Sets.

A Set is an associative container(a group of the class template in the standard library of C++) that stores unique elements.

Since it stores unique elements, so the frequency of each element is one, and duplicates are not allowed.

Sets are a part of the C++ Standard Template Library. In Sets, we can not modify the value of any element.



set<int>s   //set of  integers


s.insert(element);  //inserts an element to the set.


int length=s.size(); //returns the size of the set.


s.empty() //returns whether the set is empty.


s.max_size() //returns the maximum number of elements a set container can hold.


There are many methods in  a Set in C++,Some important methods are given below:

  • s.begin()
  • s.end()
  • s.clear()
  • s1.swap(s2)
  • s.erase(position) or s.erase(startpos,endpos)

Delete the last element from a Set

#include <iterator>
using namespace std;
int main()
  for(int i=1;i<=10;i++)
    s.insert(i*2);//insertion of element in a set
  set<int>::iterator it; //iterator
    cout<<*it<<" ";
    set<int>::iterator t;//// iterator  
    t = --s.end();//postion of the element which is going to be deleted 
    s.erase(t); //delete the last element
    set<int>::iterator p;
    cout<<*p<<" ";
  return 0;
2 4 6 8 10 12 14 16 18 20
2 4 6 10 12 14 16 18

In the above program, iterator is used

let me give a brief introduction to an iterator.

iterators are like pointers.

It points to the memory addresses of STL containers.

You can learn also about this topic:: Object Slicing in C++


Leave a Reply

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