接上一篇,sort中comp的应用

来源:互联网 发布:淘宝店铺的运营管理txt 编辑:程序博客网 时间:2024/04/29 10:59

转自http://www.cppblog.com/mzty/archive/2005/12/15/1770.html

#include <iostream>#include <algorithm>#include <functional>#include <vector>using namespace std;class myclass {        public:        myclass(int a, int b):first(a), second(b){}        int first;        int second;        bool operator < (const myclass &m)const {                return first < m.first;        }};bool less_second(const myclass & m1, const myclass & m2) {        return m1.second < m2.second;}int main() {                vector< myclass > vect;        for(int i = 0 ; i < 10 ; i ++){                myclass my(10-i, i*3);                vect.push_back(my);        }        for(int i = 0 ; i < vect.size(); i ++)         cout<<"("<<vect[i].first<<","<<vect[i].second<<")\n";        sort(vect.begin(), vect.end());        cout<<"after sorted by first:"<<endl;        for(int i = 0 ; i < vect.size(); i ++)         cout<<"("<<vect[i].first<<","<<vect[i].second<<")\n";        cout<<"after sorted by second:"<<endl;        sort(vect.begin(), vect.end(), less_second);        for(int i = 0 ; i < vect.size(); i ++)         cout<<"("<<vect[i].first<<","<<vect[i].second<<")\n";                return 0 ;}

知道其输出结果是什么了吧:

(10,0)(9,3)(8,6)(7,9)(6,12)(5,15)(4,18)(3,21)(2,24)(1,27)after sorted by first:(1,27)(2,24)(3,21)(4,18)(5,15)(6,12)(7,9)(8,6)(9,3)(10,0)after sorted by second:(10,0)(9,3)(8,6)(7,9)(6,12)(5,15)(4,18)(3,21)(2,24)(1,27)

不知道里面的functional头文件是干什么的.........谁看到可以和我讲下

原创粉丝点击