gpt4 book ai didi

c++ - 带引用键的 unordered_map

转载 作者:太空狗 更新时间:2023-10-29 21:03:32 24 4
gpt4 key购买 nike

新的 C++ unordered_map 有问题:我想使用 operator[]const键,但我被拒绝了。

我不能给出完整的代码,但我可以这样简化我的问题:

#include <unordered_map>

class A {
public:
A();
};

class B {
public:
B();
};

int main(int argc, char **argv) {
std::unordered_map<A &, B> myMap;
A a;
const A &ar = a;
B b;
myMap[ar] = b;
}

编译器的输出有点长,但结尾是:

/usr/include/c++/4.6/bits/hashtable_policy.h:537:5: note:   no known conversion for argument 1 from ‘const A’ to ‘A&’

我使用 const A &因为,在我的代码中,一些方法按原样提供给我。顺便说一句,关键应该是常量。我试过 std::unordered_map<const A &, B> myMap;相反,但它也不起作用。

我使用 gcc 4.6.3 版(Ubuntu/Linaro 4.6.3-1ubuntu5),-std=c++0x旗帜。

你能告诉我为什么这是被禁止的吗?我必须说我不明白原因。

非常感谢(如果问题很愚蠢,请原谅...)。

最佳答案

原因是 operator[] 指定如下(请注意,同样适用于 std::map):

Value& operator[](Key const& k);

在您的例子中,KeyA&,因此它扩展为:

B& operator[](A& const& k);

并且由于引用到引用是无效的,并且在通过 typedef 或模板参数创建时删除了顶级引用,您得到的只是:

B& operator[](A&);

无法处理 A const& 参数。

一般来说,我建议不要使用可变引用作为键,因为可变键是错误的良好来源。

关于c++ - 带引用键的 unordered_map,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13222459/

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