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.
Declaration
set<data_type>set_name;
set<int>s //set of integers
Insert
s.insert(element); //inserts an element to the set.
Size
int length=s.size(); //returns the size of the set.
empty()
s.empty() //returns whether the set is empty.
max_size()
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<iostream>
#include<set>
#include<algorithm>
#include <iterator>
using namespace std;
int main()
{
set<int>s;
for(int i=1;i<=10;i++)
{
s.insert(i*2);//insertion of element in a set
}
set<int>::iterator it; //iterator
for(it=s.begin();it!=s.end();it++)
{
cout<<*it<<" ";
}
cout<<endl;
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;
for(p=s.begin();p!=s.end();p++)
{
cout<<*p<<" ";
}
return 0;
}Output: 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