Possible Duplicate:
Implementing comparision operators via 'tuple' and 'tie', a good idea?
有时候我需要写一些丑陋的仿函数
例如
lhs.date_ < rhs.date_ ||
lhs.date_ == rhs.date_ && lhs.time_ < rhs.time_ ||
lhs.date_ == rhs.date_ && lhs.time_ == rhs.time_ && lhs.id_ < rhs.id_ .....
这让我很生气。
所以我开始避免这样写:
std::make_tuple( lhs.date_, lhs.time_, lhs.id_ ) <
std::make_tuple(rhs.date_, rhs.time_, rhs.id_ );
我几乎很高兴,但请注意,我可能不是出于他们的目的使用元组让我担心。
您能批评一下这个解决方案吗?
或者这是一个很好的做法?
您如何避免这种比较?
更新:
感谢您指出 std::tie 以避免复制对象。
并感谢您指出重复的问题
std::tuple
的声明比较运算符指出:
Compares lhs and rhs lexicographically, that is, compares the first elements, if they are equivalent, compares the second elements, if those are equivalent, compares the third elements, and so on.
所以你在做什么,除了有可能创建不需要的临时文件(可能优化掉)之外,对我来说似乎没问题。
请注意,等效 表示 !( lhs < rhs ) && !( rhs < lhs )
而不是 lhs == rhs
,这就是平等。假设 equivalent 和 equality 对你的类(class)意味着相同,这就没问题了。请注意,这与访问 set
没有什么不同。/map
按键。
为了避免临时的,你可以使用std::tie
这使得一个左值引用的元组指向它的参数:
std::tie( lhs.date_, lhs.time_, lhs.id_ ) <
std::tie( rhs.date_, rhs.time_, rhs.id_ );
以类似的方式,std::forward_as_tuple
生成一个右值引用的元组。