C++ const std::map reference fails to compile(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 引用无法编译
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 初始化列表*参数*评估顺序 2021-01-01
