Joe*_*ane 15 c++ stdmap std find operator-keyword
是否有理由将参数传递给std::mapas作为导致[]运算符中断?当我使用const时,我得到这个编译器错误(gcc 4.2):
错误:'map [name]'中'operator []'不匹配
这是函数原型:
void func(const char ch, std::string &str, const std::map<std::string, std::string> &map);
Run Code Online (Sandbox Code Playgroud)
而且,我应该提一下,当我删除const前面的关键字时没有问题std::map.
如果我被正确指示,[]运算符实际上会在地图中找到一个新对,如果找不到密钥,这当然可以解释为什么会发生这种情况,但我无法想象这会是可接受的行为
如果有更好的方法,比如使用find代替[],我会很感激.我似乎无法找到工作,虽然...我收到const不匹配的迭代器错误.
Joh*_*itb 26
是的,你不能使用operator[].使用find,但请注意它返回const_iterator而不是iterator:
std::map<std::string, std::string>::const_iterator it;
it = map.find(name);
if(it != map.end()) {
std::string const& data = it->second;
// ...
}
Run Code Online (Sandbox Code Playgroud)
就像指针一样.你不能分配int const*给int*.同样的,你不能分配const_iterator给iterator.
当您使用operator []时,std :: map会查找具有给定键的项目.如果找不到,则创建它.因此const的问题.
使用find方法,你会没事的.
你能否发布关于你如何使用find()的代码?正确的方法是:
if( map.find(name) != map.end() )
{
//...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12736 次 |
| 最近记录: |