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 引用无法编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Rising edge interrupt triggering multiple times on STM32 Nucleo(在STM32 Nucleo上多次触发上升沿中断)
How to use va_list correctly in a sequence of wrapper functions calls?(如何在一系列包装函数调用中正确使用 va_list?)
OpenGL Perspective Projection Clipping Polygon with Vertex Outside Frustum = Wrong texture mapping?(OpenGL透视投影裁剪多边形,顶点在视锥外=错误的纹理映射?)
How does one properly deserialize a byte array back into an object in C++?(如何正确地将字节数组反序列化回 C++ 中的对象?)
What free tiniest flash file system could you advice for embedded system?(您可以为嵌入式系统推荐什么免费的最小闪存文件系统?)
Volatile member variables vs. volatile object?(易失性成员变量与易失性对象?)