在对于vector里的结构体用sort排序的时候,一般有两种方法,一种是重载操作符 ‘<’ 另一种是写一个 cmp 函数,下面代码举例说明
#include <iostream>
#include<vector>
#include <algorithm>
using namespace std;
struct point{
int x;
int y;
point(int _x, int _y):x(_x), y(_y){}
};
bool operator < (const point a, const point b){
return a.x==b.x?a.y<b.y:a.x<b.x;
}
bool cmp(const point a, const point b){
return a.x==b.x?a.y>b.y:a.x>b.x;
}
void init_v(vector<point> &point_v){
point_v.push_back(point(1,4));
point_v.push_back(point(3,5));
point_v.push_back(point(1,3));
point_v.push_back(point(2,5));
}
int main()
{
int x = 0;
vector<point> point_v;
init_v(point_v);
cout<<"重载运算符,从小到大"<<endl;
sort(point_v.begin(), point_v.end());
for (int i = 0; i < point_v.size(); ++i) {
cout<<point_v[i].x<<" "<<point_v[i].y<<endl;
}
point_v.clear();
init_v(point_v);
cout<<"编写cmp函数,从大到小"<<endl;
sort(point_v.begin(), point_v.end(), cmp);
for (int i = 0; i < point_v.size(); ++i) {
cout<<point_v[i].x<<" "<<point_v[i].y<<endl;
}
return 0;
}
结果如下:
重载运算符,从小到大
1 3
1 4
2 5
3 5
编写cmp函数,从大到小
3 5
2 5
1 4
1 3