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;
} 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值