日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

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

编程问答

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

發布時間:2024/9/30 编程问答 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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中各种容器的自定义比较函数的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。