优选实施'''用于多变量结构 [英] Preferred implementation of '<' for multi-variable structures

查看:104
本文介绍了优选实施'''用于多变量结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最初,这可能看起来过于抽象或哲学,但我真的很感兴趣,看看有人有一个令人信服的论据赞成一个实现的另一个。



给定运算符< std :: pair< T1,T2> ,这将是更好的实现:

  return x.first< y.first || 
x.first == y.first&&& x。 y.second;

或:

 code> return x.first< y.first || 
!(y.first< x.first)&&& x。 y.second;

我的理解是两个实现产生相同的结果。后者是否优选,因为它仅仅以运算符<的形式定义?或者是合理假设一个小于可比的类型也应该是平等的?有没有其他人看到另一个点,会摇摆你之间一个或另一个?



自然地,任何答案应该是通用的和可扩展的。那么你会使用哪一个,为什么?

解决方案

假设对于任何类型,如果它小于可比的,它也是等同的,因为可以重载 operator 但不重载 operator ==



因此,如果您预计必须处理用户定义的类型,则第二种方法是更可取的。但是,您应该添加一些括号以说明操作顺序:

  return x.first< y.first || 
(!(y.first< x.first)&& x.second< y.second);


Initially this may seem overly abstract or philosophical, but I am genuinely interested to see if someone has a convincing argument in favor of one implementation over the other.

Given operator< for std::pair<T1, T2>, which would be the better implementation:

return x.first < y.first ||
       x.first == y.first && x.second < y.second;

or:

return x.first < y.first ||
       !(y.first < x.first) && x.second < y.second;

My understanding is that the two implementations yield equivalent results. Is the latter preferred because it is defined solely in terms of operator<? Or is it legitimate to assume that a type that is less-than comparible should also be equality comparable? Does anyone else see another point that would sway you between one or the other?

Naturally any answer should be both generic and extensible. So which one would you use and why? Is there a different implementation that's even better than the above?

解决方案

It is not legitimate to assume that for any type, if it is less-than comparable, it is also equality comparable, since one can overload operator< but not overload operator==.

Thus, if you anticipate having to handle user-defined types, the second approach is preferable. However, you should add some parentheses to clarify the order of operations:

return x.first < y.first ||
       (!(y.first < x.first) && x.second < y.second);

这篇关于优选实施'''用于多变量结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆