C++ const std::map 引用无法编译

C++ const std::map reference fails to compile(C++ const std::map 引用无法编译)

本文介绍了C++ const std::map 引用无法编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::map 的引用作为 const 传递是否会导致 [] 运算符中断?使用 const 时出现此编译器错误(gcc 4.2):

Is there a reason why passing a reference to a std::map as const causes the [] operator to break? I get this compiler error (gcc 4.2) when I use const:

错误:没有匹配到‘operator[]’‘地图[名称]’

error: no match for ‘operator[]’ in ‘map[name]’

这是函数原型:

void func(const char ch, std::string &str, const std::map<std::string, std::string> &map);

而且,我要提一下,当我去掉 std::map 前面的 const 关键字时没有问题.

And, I should mention that there is no problem when I remove the const keyword in front of std::map.

如果我的指示正确,如果 [] 运算符找不到密钥,它实际上会在映射中插入一个新对,这当然可以解释为什么会发生这种情况,但我无法想象这永远是可以接受的行为.

If I've been instructed correctly, the [] operator will actually insert a new pair into the map if it doesn't find the key, which would of course explain why this happens, but I can't imagine that this would ever be acceptable behavior.

如果有更好的方法,比如使用 find 而不是 [],我将不胜感激.我似乎也无法找到工作...我收到 const 不匹配的迭代器错误.

If there is a better method, like using find instead of [], I'd appreciate it. I can't seem to get find to work either though... I receive const mismatched iterator errors.

推荐答案

是的,你不能使用 operator[].使用 find,但注意它返回 const_iterator 而不是 iterator:

Yes you can't use operator[]. Use find, but note it returns const_iterator instead of iterator:

std::map<std::string, std::string>::const_iterator it;
it = map.find(name);
if(it != map.end()) {
    std::string const& data = it->second;
    // ...
}

就像指针一样.您不能将 int const* 分配给 int*.同样,您不能将 const_iterator 分配给 iterator.

It's like with pointers. You can't assign int const* to int*. Likewise, you can't assign const_iterator to iterator.

这篇关于C++ const std::map 引用无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:C++ const std::map 引用无法编译

基础教程推荐