c++ list vector 结构体排序
第一次写博客, 记录一下用c++的时候发现的问题
结构体排序一般都用到模板
algorithm头文件里边有排序模板
调用sort方法
需要对某个属性排序的话, 需要重载比较器
直接上代码
#include <iostream>
#include <algorithm>
#include <list>
#include <vector>
using namespace std;
typedef struct POINT {
int x;
int y;
} point;
//按照x排序
bool compareX(const point &p1, const point &p2) {
if(p1.x < p2.x)
return true;
else
return false;
}
//按照y排序
bool compareY(const point &p1, const point &p2) {
return p1.y < p2.y;
}
int main() {
point p1, p2, p3, p4, p5;
p1.x = 2;
p1.y = 1;
p2.x = 4;
p2.y = 6;
p3.x = 3;
p3.y = 9;
p4.x = 10;
p4.y = 1;
p5.x = 8;
p5.y = 4;
list<point> ls;
ls.push_back(p1);
ls.push_back(p2);
ls.push_back(p3);
ls.push_back(p4);
ls.push_back(p5);
vector<point> ve;
ve.push_back(p1);
ve.push_back(p2);
ve.push_back(p3);
ve.push_back(p4);
ve.push_back(p5);
// sort(ls.begin(), ls.end(), compareX); //错误, 提示没有重载-号
// sort(ls.begin(), ls.end(), compareY); //错误, 提示没有重载减号
// sort(ve.begin(), ve.end(), compareX); //正确
// ls.sort(compareY); //正确
for(list<point>::iterator it = ls.begin(); it != ls.end(); it ++) {
cout << "(" << it->x << " ," << it->y << " )" << endl;
}
return 0;
}
由代码可以看出, list不能使用这个模板进行排序
需要用list自带的sort方法排序
原因不详, 希望有大佬指点