[英]Why don't unordered associative containers implement the less than operator?
The unordered associative containers unordered_set
, unordered_map
etc do not have a less than operator operator<
, neither as a member function nor as a free function. 无序关联容器unordered_set
, unordered_map
等没有小于运算operator<
运算operator<
,既不是成员函数也不是自由函数。 Why? 为什么? There is no specialization of less
either. 没有专业化less
无论是。 SGI STL's hash_*
types also lack this feature. SGI STL的hash_*
类型也缺少此功能。
If we exclude the concept of underlying types, all container types fulfil the requirements of regular types as defined eg in Stepanov & McJones' Elements of Programming . 如果我们排除底层类型的概念,所有容器类型都满足常规类型的要求,例如Stepanov&McJones 的编程元素 。 The sole exception are the unordered associative types, which lack operator<
. 唯一的例外是无序的关联类型,它缺少operator<
。
I could not come up with an efficient implementation of such an operator that is consistent with the given definition of equality, so might efficiency be the reason? 我无法想出一个与给定的平等定义一致的运算符的有效实现,那么效率可能是什么原因呢? On the other hand, operator==
for unordered associative containers in some cases needs to rehash every element of one container and look it up in the other - O(N) average, but worst case O(N²). 另一方面, operator==
对于无序关联容器,在某些情况下需要重新散列一个容器的每个元素并在另一个容器中查找 - O(N)平均值,但最差情况为O(N²)。
Conceptually it doesn't make a lot of sense. 从概念上讲,它没有多大意义。 Consider a bag of different colored marbles. 考虑一袋不同颜色的大理石。 And lets say you have two bags of marbles: 让我们说你有两袋大理石:
Is bag 1 < bag 2? 袋1 <袋2?
Even if you associate an order to the colors, say: 即使您将订单与颜色相关联,也请说:
red < yellow < purple < blue < green
It is still difficult to say if one bag is less than than the other because internally the bag associates no order to the marbles. 仍然很难说一个袋子是否小于另一个袋子,因为袋子里面没有任何订单与大理石相关联。 That is bag 1 could be output in any of 6 formats, which are all equivalent: 也就是说,包1可以以6种格式中的任何一种输出,这些格式都是等价的:
None of the above six are less than any of the other. 以上六种都不比其他任何一种都少。 Indeed, they are all equal, no matter whether red < blue or blue < red. 实际上,无论是红色还是蓝色<红色,它们都是平等的。 A bag is not a sequence ... it is an unordered sequence. 一个包不是一个序列......它是一个无序的序列。
Historically the unordered containers also did not have equality operators. 从历史上看,无序容器也没有相等的运算符。 However it does make sense to ask if one bag contains the same colored marbles as another bag. 然而,询问一个袋子是否包含与另一个袋子相同的彩色大理石是有意义的。 And here the issue is one of efficiency. 这里的问题是效率问题。 Eventually algorithms and proposals were presented to sway the committee to add equality comparisons for the unordered containers: 最终提出了算法和提议,以动摇委员会为无序容器添加相等比较:
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3068.pdf http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2010/n3068.pdf
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.