更新时间:2022-12-06 11:07:34
这是一个相当古老的问题,因此所有的答案都是过时的。 C ++ 11允许更加优雅和高效的解决方案:
This is quite an old question and as a consequence all answers here are obsolete. C++11 allows a more elegant and efficient solution:
bool operator <(const MyStruct& x, const MyStruct& y) {
return std::tie(x.a, x.b, x.c) < std::tie(y.a, y.b, y.c);
}
为什么比使用 boost :: make_tuple
?因为 make_tuple
将创建所有数据成员的副本,这可能是昂贵的。相比之下, std :: tie
,将只创建一个引用的薄包装(编译器可能会完全优化)。
Why is this better than using boost::make_tuple
? Because make_tuple
will create copies of all the data members, which can be costly. std::tie
, by contrast, will just create a thin wrapper of references (which the compiler will probably optimise away entirely).
事实上,上面的代码现在应该被视为实现对具有多个数据成员的结构的词典比较。
In fact, the above code should now be considered the idiomatic solution to implementing a lexicographical compare for structures with several data members.