gpt4 book ai didi

c++ - 使用集合作为键映射的机制

转载 作者:行者123 更新时间:2023-11-28 00:21:12 25 4
gpt4 key购买 nike

我有这段代码,但我不明白它为什么有效:

map<set<int>,int> states;
set<int> s1 = {5,1,3}, s2 = {1,5,3};
states[s1] = 42;
printf("%d", states[s2]); // 42

输出为 42,因此 states 键的值以某种方式用于比较。这怎么可能?我希望这不会像类似示例中那样工作:

map<const char*,int> states;
char s1[]="foo", s2[]="foo";
states[s1] = 42;
printf("%d",states[s2]); // not 42

这里使用的是char指针的地址作为key,而不是它指向的内存的值,对吧?请解释这两个示例之间的区别。

编辑:我刚刚发现了一些关于 comparison object 的信息这解释了很多。但是集合的比较对象是如何创建的呢?我看不出它怎么可能是默认的 less 对象。

最佳答案

您对比较对象有所了解。
C++的模板参数之一 map 定义什么作为比较谓词,默认情况下 std::less<Key> , 在这种情况下 std::less<set<int>> .

来自 cplusplus.com :

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.

std::less :

Binary function object class whose call returns whether the its first argument compares less than the second (as returned by operator <). std::set::key_comp: By default, this is a less object, which returns the same as operator<.

现在,what does the less-than operator do? :

The less-than comparison (operator<) behaves as if using algorithm lexicographical_compare, which compares the elements sequentially using operator< in a reciprocal manner (i.e., checking both a<b and b<a) and stopping at the first occurrence.

或来自MSDN :

The comparison between set objects is based on a pairwise comparison of their elements. The less-than relationship between two objects is based on a comparison of the first pair of unequal elements.

所以,因为这两个集合是等价的,因为 set s 按键排序,使用任一个作为键指代映射中的相同条目。
但是第二个示例使用指针作为键,因此就映射而言,两个等效值并不相等,因为 operator<在这种情况下,没有以任何特殊方式定义,它只是地址之间的比较。如果您使用了 std::string作为关键,他们会匹配,虽然(因为他们有自己的 operator< )。

关于c++ - 使用集合作为键映射的机制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27392548/

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