STL——list容器

#include<list>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	list<int> l;
	//鏈表尾部插入新元素,鏈表自動擴張 
	l.push_back(2);
	l.push_back(1);
	l.push_back(5);
	//在鏈表頭部插入元素,鏈表自動擴張 
	l.push_front(8);
	list<int>::iterator it;
	it=l.begin();
	it++;
	l.insert(it,20);
	for(it=l.begin();it!=l.end();it++){
		cout<<*it<<" ";
	} 
	cout<<endl;
	
	/*反向遍歷*/
	list<int>::reverse_iterator rit;
	for(rit=l.rbegin();rit!=l.rend();rit++){
		cout<<*rit<<" ";
	} 
	cout<<endl;
	
	/*元素刪除——remove()方法*/
	list<int> ll;
	ll.push_back(2);
	ll.push_back(1);
	ll.push_back(5);
	ll.push_back(1);
	list<int>::iterator it2;
	for(it2=ll.begin();it2!=ll.end();it2++){
		cout<<*it2<<" ";
	}
	cout<<endl;
	ll.remove(1);
	for(it2=ll.begin();it2!=ll.end();it2++){
		cout<<*it2<<" ";
	}
	cout<<endl;
	
	/*元素刪除——pop_front()方法刪除鏈表首元元素,pop_back()方法刪除鏈表尾元素*/ 
	list<int> l1;
	l1.push_back(2);
	l1.push_back(8);
	l1.push_back(1);
	l1.push_back(5);
	l1.push_back(1);
	list<int>::iterator it3;
	for(it3=l1.begin();it3!=l1.end();it3++){
		cout<<*it3<<" ";
	} 
	cout<<endl;
	l1.pop_front();
	l1.pop_back();
	for(it3=l1.begin();it3!=l1.end();it3++){
		cout<<*it3<<" ";
	} 
	
	it3=l1.begin();
	it3++;
	it3++;
	l1.erase(it3);
	for(it3=l1.begin();it3!=l1.end();it3++){
		cout<<*it3<<" ";
	}   
	cout<<endl;        
	
	/*clear()方法*/
	l1.clear();
	cout<<l1.size()<<endl;   
	
	list<int> l2;
	l2.push_back(2);
	l2.push_back(8);
	l2.push_back(1);
	l2.push_back(5);
	l2.push_back(1);
	list<int>::iterator it4,it5;
	for(it4=l2.begin();it4!=l2.end();it4++){
		cout<<*it4<<" ";
	}  
	cout<<endl;
	//採用find()查找算法在鏈表中查找
	it4=find(l2.begin(),l2.end(),5);
	if(it4!=l2.end()){
		cout<<"find it"<<endl;
	} 
	else{
		cout<<"not find"<<endl;
	}
	it4=find(l2.begin(),l2.end(),10);
	if(it4!=l2.end()){
		cout<<"find it"<<endl;
	}
	else{
		cout<<"not find it"<<endl;
	}
	
	/*元素排序*/
	l2.sort();
	for(it4=l2.begin();it4!=l2.end();it4++){
		cout<<*it4<<" ";
	} 
	cout<<endl;
	
	/*剔除連續重複的元素*/
	l2.unique(); 
	for(it4=l2.begin();it4!=l2.end();it4++){
		cout<<*it4<<" "; 
	}
	cout<<endl;
	
	
	return 0;
} 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章