c++ - 使用 make_tuple 进行比较

标签 c++ c++11 tuples idioms

<分区>

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 ,这就是平等。假设 equivalentequality 对你的类(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生成一个右值引用的元组。

关于c++ - 使用 make_tuple 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10806036/

相关文章:

c++ - using 声明的可变参数扩展

c++ - 在结构上应用 std 算法?

C++ 使用统计

c++ - 无法从 'SDL_Surface' 转换为 'SDL_Surface MainMenu::*'

c++ - 将非托管 C++ 代码编译为托管代码

python - 按列表中元组的顺序将多个元组列表组合成新的元组列表(python3)

python - 为什么我不能在 python3 中子类化元组?

c++ - 如何在 C++ 中修改 unordered_map 中的每个值

c++ - std::bind2nd 的替代品

c++ - boost::recursive_wrapper 和 std::unique_ptr