《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个的时候,表达式已经很复杂了。