list

来源:互联网 发布:ipad看淘宝直播 编辑:程序博客网 时间:2024/06/05 10:07

要排序一个list,我们要用list的成员函数sort(),而不是通用算法sort()。


list容器有它自己的sort算法,这是因为通用算法仅能为那些提供随机存取里面元素 的容器排序。


list的成员函数push_front()和push_back()分别把元素加入到list的前面和后面。你可以使用insert() 把对象插入到list中的任何地方。


insert()可以加入一个对象,一个对象的若干份拷贝,或者一个范围以内的对象。


list成员函数pop_front()删掉list中的第一个元素,pop_back()删掉最后一个元素。函数erase()删掉由一个iterator指出的元素。还有另一个erase()函数可以删掉一个范围的元素。


list的成员函数remove()用来从list中删除元素。

*.remove("要删除的对象");

通用算法remove()使用和list的成员函数不同的方式工作。一般情况下不改变容器的大小。

remove(*.begin(),*.end(),"要删除的对象");


使用STL通用算法stable_partition()和list成员函数splice()来划分一个list。

stable_partition()是一个有趣的函数。它重新排列元素,使得满足指定条件的元素排在不满足条件的元素前面。它维持着两组元素的顺序关系。

splice 把另一个list中的元素结合到一个list中。它从源list中删除元素。


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

const string hadoopcode("0001");

/*
class IsAHadoop{
public:
bool operator() (string &hadoop){
return hadoop.substr(0,4) ==hadoopcode;
}
};
*/
int IsAHadoop(string &hadoop){
return hadoop.substr(0,4)==hadoopcode;
}


void PrintIt(string &str){
cout<<str<<" "<<ends;
}

int IsAHive(string &hive){
return hive.substr(0,4)=="0002";
}

int main(){
list<string> mylist;
list<string>::iterator itbegin = mylist.begin();
mylist.push_back("0001 hadoop");
mylist.push_back("0002 hive");
mylist.push_front("0003 pig");
mylist.push_front("0001 hadoop");
mylist.push_front("0004 zookeeper");
        mylist.insert(itbegin , 3,"0001 hadoop");

/**************empty()***************/
if(!mylist.empty()){
cout<<"mylist is not empty!!"<<"  size: "<<mylist.size()<<endl;
}
/***************iterator*************/
list<string>::iterator it;
for(it=mylist.begin();it!= mylist.end();++it){
cout<<*it<<"-->"<<ends;
}
cout<<endl;
/***************count()***************/
int numofpig=count(mylist.begin(),mylist.end(),"0003 pig");
cout<<"num of pig is "<<numofpig<<endl;
/***************count_if()**************/
int NumofHadoop(0);
string hadoopstr("0003");
NumofHadoop =count_if(mylist.begin(),mylist.end(),IsAHadoop);
cout<<"there were "<<NumofHadoop<<" hadoop matching code"<<hadoopstr<<endl;
/****************for_each()***********/
for_each(mylist.begin(),mylist.end(),PrintIt);
/***************find()****************/
list<string>::iterator itf;
itf=find(mylist.begin(),mylist.end(),"0003 pig");
if(itf==mylist.end())
cout<<"can not find!!"<<endl;
else
cout<<"find......"<<*itf<<endl;
/***************find_if()*************/
itf=find_if(mylist.begin(),mylist.end(),IsAHive);
 if(itf==mylist.end())
                cout<<"can not find!!"<<endl;
        else
                cout<<"find......"<<*itf<<endl;
return 0;
}

0 0
原创粉丝点击