如果我有一个我希望能够排序的类(即支持小于概念),并且它有几个数据项,因此我需要进行字典排序,那么我需要这样的东西:
struct MyData {
string surname;
string forename;
bool operator<(const MyData& other) const {
return surname < other.surname || (surname==other.surname && forename < other.forename); }
};
这对于拥有超过 2 个数据成员的任何事物来说变得非常难以管理。有没有更简单的方法来实现它?数据成员可以是任何 Comparable 类。
最佳答案
随着 C++11 的出现,使用 std::tie 有一种新的简洁的方法来实现这一点。 :
bool operator<(const MyData& other) const {
return std::tie(surname, forename) < std::tie(other.surname, other.forename);
}
关于c++ - 为类元素定义字典比较的最简单方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2500664/