algorithm中sort函数的使用

来源:互联网 发布:wavecom短信猫软件 编辑:程序博客网 时间:2024/05/18 04:59

知识点:

只有定义为vector<int>型变量,才可以使用第一种形式;

第二种形式,需自己定义数组元素比较大小的方式,函数返回类型为bool,调用时,只需函数名,不要加()

sort(a.begin(),a.end)sort(a.begin(),a.end,myfun)

#include<iostream>#include<vector>#include<algorithm>using namespace std;typedef struct{int val;}node;bool great(node a, node b){return a.val < b.val;}bool les(node a, node b){return a.val > b.val;}void print(vector<node> a){for (node t:a){cout << t.val << ' ';}cout << endl;}int main(){vector<node> vec(4);vec[0].val = 3;vec[1].val = 2;vec[2].val = 1;vec[3].val = 5;cout << "初始数据" << endl;print(vec);sort(vec.begin(),vec.end(),great);cout << "升序排列" << endl;print(vec);sort(vec.begin(), vec.end(),les);cout << "降序排列" << endl;print(vec);system("pause");return 0;}