STLSet all operation example code in C++ Linux

Set is an associated template container. Only values are stored in set.Once value inserted can not be modified.If want to modify then first erase then modify. In map using at() or [] we can directly insert new value. Values are stored in sorted ascending order. Effect of inserting a duplicate value does nothing.
#include<iostream>
using namespace std;
#include<set>
#include<algorithm>
int main()
{
cout<<"Creating an empty set:"<<endl;
set<int> set;
cout<<"Inserting into a set"<<endl;
set.insert(11);
set.insert(33);
set.insert(22);
set.insert(55);
set.insert(44);//does nothing
set.insert(44);//does nothing
set.insert(44);//does nothing

cout<<"iTraversing through into a set"<<endl;
std::set<int>::iterator itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";

cout<<"Searching in a set"<<endl;
itr=set.begin();
itr=set.find(55);
if(itr!=set.end())
cout<<"55 found"<<endl;
else
cout<<"55 not found"<<endl;

cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";


cout<<"finding and deleting from a set"<<endl;
itr=set.begin();
itr=set.find(22);
if(itr!=set.end())
{
cout<<"22 found"<<endl;
set.erase(22);
//itr=set.erase(22);//change to other itr2
}
else
{
cout<<"22 not found"<<endl;
}

set.erase(22);//deleting again no effect
cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";


cout<<"Deleting a range"<<endl;
std::set<int>::iterator itr2=set.begin();
std::set<int>::iterator itr3=set.end();
set.erase(itr2,itr3);

cout<<"Traversing"<<endl;
itr=set.begin();
for(itr;itr!=set.end();itr++)
cout<<*itr<<" ";

cout<<""<<endl;
return 0;
}
/*
Creating an empty set:
Inserting into a set
iTraversing through into a set
11 22 33 44 55 Searching in a set
55 found
Traversing
11 22 33 44 55 finding and deleting from a set
22 found
Traversing
11 33 44 55 Deleting a range
Traversing

*/

No comments:

Post a Comment