c++ list vector 结构体排序问题

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方法排序
原因不详, 希望有大佬指点

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值