《C++标准程序库》读书笔记2012-08-11 排序仿函数的设计规则

《C++标准程序库》p175页讲解了排序仿函数的设计规则
1,必须是“反对称的”
对于operator<而言,如果x < y为真,则y < x为假。

2,必须是“可传递的”
对于operator<而言,如果x < y为真且y < z为真,则x < z为真。

3,必须是“非自反的”
对于operator<而言,x < x永远为假

根据这三个规则,对于以结构体为key的情况,自定义的operator<需要如下设计:

//对于有两个成员的结构体:
struct IndexItem
{
	long time;
	int count;
};

bool operator<(const IndexItem& lh, const IndexItem& rh) {
	return (lh.time < rh.time) ||
		( (lh.time == rh.time) && (lh.count < rh.count) );
}
//对于有三个成员的结构体:
struct IndexItem
{
	long time;
	int count;
	std::string name;
};

bool operator<(const IndexItem& lh, const IndexItem& rh) {
	return (lh.time < rh.time) ||
		( (lh.time == rh.time) && ( (lh.count < rh.count) || 
		( (lh.count == rh.count) && (lh.name < rh.name) ) ) );
}
//对于有四个成员的结构体:
struct IndexItem
{
	long time;
	int count;
	int other;
	std::string name;
};

bool operator<(const IndexItem& lh, const IndexItem& rh) {
	return (lh.time < rh.time) ||
		( (lh.time == rh.time) && ( (lh.count < rh.count) || 
		( (lh.count == rh.count) && ( (lh.other < rh.other) || 
		( (lh.other == rh.other) && (lh.name < rh.name) ) ) ) ) );
}
//对于有五个成员的结构体:
struct IndexItem
{
	long time;
	int count;
	int other;
	int action;
	std::string name;
};

bool operator<(const IndexItem& lh, const IndexItem& rh) {
	return (lh.time < rh.time) ||
		( (lh.time == rh.time) && ( (lh.count < rh.count) || 
		( (lh.count == rh.count) && ( (lh.other < rh.other) || 
		( (lh.other == rh.other) && ( (lh.action < rh.action) || 
		( (lh.action == rh.action) && (lh.name < rh.name) ) ) ) ) ) ) );
}

可以看出当成员为5个的时候,表达式已经很复杂了。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值