gpt4 book ai didi

c++ - 为什么 std::map 重载运算符 < 不使用比较

转载 作者:可可西里 更新时间:2023-11-01 17:50:31 25 4
gpt4 key购买 nike

来自 http://www.cplusplus.com/reference/map/map/operators/我注意到:

“请注意,这些操作均未考虑任一容器的内部比较对象,而是直接比较元素(value_type 类型)。”

这就是说重载运算符“<”没有使用 Compare在其声明中(引用http://www.cplusplus.com/reference/map/map/)

std::map
template < class Key, // map::key_type
class T, // map::mapped_type
class Compare = less<Key>, // map::key_compare
class Alloc = allocator<pair<const Key,T> > // map::allocator_type
> class map;

哪里Compare

Compare: A binary predicate that takes two element keys as arguments and returns a bool. The expression comp(a,b), where comp is an object of this type and a and b are key values, shall return true if a is considered to go before b in the strict weak ordering the function defines. The map object uses this expression to determine both the order the elements follow in the container and whether two element keys are equivalent (by comparing them reflexively: they are equivalent if !comp(a,b) && !comp(b,a)). No two elements in a map container can have equivalent keys. This can be a function pointer or a function object (see constructor for an example). This defaults to less<T>, which returns the same as applying the less-than operator (a<b). Aliased as member type map::key_compare.

不太明白,为什么不直接用Compare呢?在“<”运算符中?

最佳答案

Compare用于比较 key_type . map 的<运算符实际上是在比较 mapped_type value_type , 不是 key_type , 所以 Compare将不适用。 value_type是一对 key_typemapped_type .

老实说,我认为给 map 一个 operator<首先是运算符重载过度的情况。说一张 map “小于”另一张 map 是什么意思并不是很明显。如果你想要lexigraphical_compare ,我建议直接调用它,或者至少在代码中记录 map 比较的含义。

关于c++ - 为什么 std::map 重载运算符 < 不使用比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27800181/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com