欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程资源 > 编程问答 >内容正文

编程问答

stl中各种容器的自定义比较函数

发布时间:2024/9/30 编程问答 36 豆豆
生活随笔 收集整理的这篇文章主要介绍了 stl中各种容器的自定义比较函数 小编觉得挺不错的,现在分享给大家,帮大家做个参考.

class elem { public:elem();elem(int aa):a(aa){} public:int a;int getA(){return a;} };class elem1 { public:elem1();elem1(int aa):a(aa){} public:int a;int getA(){return a;}friend bool operator < (const elem1 &e1,const elem1 &e2)//只能重载<{return e1.a <e2.a;//大顶堆是<;小顶堆是>} };class Scorer { public:bool operator ()(const elem &e1,const elem &e2){return e1.a<e2.a;} }; bool Cmp(const elem &e1,const elem &e2) {return e1.a <e2.a; } int main() {vector<elem> ve;ve.push_back(elem(5));ve.push_back(elem(6));ve.push_back(elem(7));ve.push_back(elem(1));ve.push_back(elem(0));ve.push_back(elem(19));ve.push_back(elem(60));ve.push_back(elem(61));ve.push_back(elem(2));ve.push_back(elem(68));ve.push_back(elem(9));list<elem> le;le.push_back(elem(5));le.push_back(elem(6));le.push_back(elem(7));le.push_back(elem(1));le.push_back(elem(0));le.push_back(elem(19));le.push_back(elem(6));priority_queue<int,vector<int>,less<int> > pq;//大顶堆//优先队列如果用仿函数的形式,必须有三个参数pq.push(5);pq.push(6);pq.push(1);pq.push(2);pq.push(9);/*while (!pq.empty()){int t = pq.top();cout<<t<<" ";pq.pop();}*/priority_queue<elem,vector<elem>,Scorer > q;//1.自定义仿函数,也要有三个参数q.push(5);q.push(6);q.push(1);q.push(2);q.push(9);priority_queue<elem1> q1;//2.q1.push(5);q1.push(6);q1.push(1);q1.push(2);q1.push(9);set<int,less<int> > s;//从小到大s.insert(5);s.insert(6);s.insert(1);s.insert(3);s.insert(0);set<elem,Scorer> s1;s1.insert(5);s1.insert(6);s1.insert(1);s1.insert(3);s1.insert(0);set<elem,Scorer >::iterator it;for (it = s1.begin();it!=s1.end();++it){cout<<it->getA()<<" ";}/*while(!q1.empty()){elem1 e = q1.top();cout<<e.getA()<<" ";q1.pop();}*/int array[] = {5,6,7,1,0,19,6};sort(array,array+7,greater<int>());//less<int>() 从小到大//说明greater,less和Scorer一样都是类,而Cmp是函数;所以vector还是用Cmp形式的函数比较方便/*for (int i=0;i<7;++i){cout<<array[i]<<" ";}cout<<endl;*///sort(ve.begin(),ve.end(),Scorer());//sort(ve.begin(),ve.end(),Cmp);//partial_sort(ve.begin(),ve.begin()+3,ve.end(),Cmp);//对前三个排序nth_element(ve.begin(),ve.begin()+3,ve.end(),Cmp);//保证前三个最小,前三个不排序//sort(le.begin(),le.end(),Cmp);le.sort(Scorer());//Cmp//list的排序是要移动其内部指针的,所以只能用其内部的sort,而不能用通用的sort//也不能用nth_elements之类的排序/*vector<elem>::iterator it;for (it = ve.begin();it!=ve.end();++it){cout<<it->getA()<<" ";}*/cout<<endl;}
stl中各种容器的自定义比较函数的方法,vector,list,set相类似,要定义一个比较类,类里面有比较成员函数 bool operator ()(const,const),并且return a<b 是从小到大排序

priority_queue有些不同,主要表现在return a<b是大顶堆


所有的共同之处是,都可以通过定义一个比较类实现排序




总结

以上是生活随笔为你收集整理的stl中各种容器的自定义比较函数的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。