C++ list example. All operations.

#include<iostream>
using namespace std;
#include<list>
#include<algorithm>

int main()
{
//creating an empty list
list<int> l;
//Way:1 to insert
l.push_back(10);
l.push_back(100);
l.push_back(20);
//Way:2 to insert

list<int>::iterator itr=l.begin();
while(itr!=l.end())
{
cout<<*itr<<"\t";
itr++;
}

cout<<""<<endl;
//Way:2 creating a list with fixed size 5
list<string> ls2(5);
list<string>::iterator itr2=ls2.begin();
while(itr2!=ls2.end())
{
cout<<*itr2<<"\t";
itr2++;
}

cout<<""<<endl;
//Way:2 creating a list with fixed size 5 with initial value "Mr"
list<string> ls3(5,"Mr");
list<string>::iterator itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<""<<endl;

ls3.push_back("Mr");
ls3.push_back("Mr");
ls3.push_back("Mrs");
ls3.push_back("Miss");
ls3.push_back("Mrs");

cout<<"Way 0: to remove by value"<<endl;
ls3.remove("Mr");//deletes all a value "Mr"
itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}


itr3=ls3.begin();
cout<<"Way 1: to erase single value by itr"<<endl;
list<string>::iterator itr4=ls3.begin();
itr3=ls3.erase(itr4);//1th element deleted
itr3=ls3.begin();
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<"\nWay 2: to erase range by iterator"<<endl;
itr3=ls3.begin();
list<string>::iterator itr5=ls3.begin();
list<string>::iterator itr6=ls3.end();
itr3=ls3.erase(itr5,itr6);//deletes begin to end
while(itr3!=ls3.end())
{
cout<<*itr3<<"\t";
itr3++;
}
cout<<""<<endl;

return 0;
}
/*
10      100     20     
Mr      Mr      Mr      Mr      Mr     
Way 0: to remove by value
Mrs     Miss    Mrs     Way 1: to erase single value by itr
Miss    Mrs    
Way 2: to erase range by iterator
*/

No comments:

Post a Comment