可以通过实现std::less
模板类来定义部分结构体之间的排序关系。例如,以下示例定义了一个Person
结构体,其中仅定义了name
和age
字段。如果要对Person
对象进行排序,则必须定义比较函数operator<
,否则编译器会报错。
#include
#include
struct Person {
std::string name;
int age;
};
// 定义 less 模板类,指定比较函数 operator<
template
struct less {
bool operator()(const T& a, const T& b) const {
return a < b; // 此处调用 operator<
}
};
// 定义 Person 对象的 operator<
bool operator<(const Person& a, const Person& b) {
if (a.name < b.name) return true;
if (a.name > b.name) return false;
return a.age < b.age;
}
int main() {
Person a {"Alice", 20};
Person b {"Bob", 30};
Person c {"Charlie", 10};
std::cout << (less{}(a, b) ? "a < b" : "a >= b") << std::endl; // a >= b
std::cout << (less{}(a, c) ? "a < c" : "a >= c") << std::endl; // a >= c
std::cout << (less{}(b, c) ? "b < c" : "b >= c") << std::endl; // b >= c
return 0;
}
输出:
a >= b
a >= c
b >= c