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

问题描述

有一个原因,为什么传递引用STL映射作为const导致[]运算符破裂?我使用const时得到这个编译器错误(gcc 4.2):

这是函数原型:

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

而且,我应该提到当我删除 const 。



如果我被正确指示,[]操作符将实际插入一个新对如果它没有找到钥匙,这当然会解释为什么会发生,但我不能想象这将是可以接受的行为。



如果有一个更好的方法,如使用 find 而不是[],我会很感激。我似乎无法找到工作,不过...我收到 const 不匹配的迭代器错误。



谢谢。

解决方案

是的,您不能使用 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;
// ...
}

就像指针。您不能将 int const * 分配给 int * 。同样,您不能将 const_iterator 分配给迭代器


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

Here's the function prototype:

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

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.

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.

Thanks.

解决方案

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;
    // ...
}

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

08-10 23:40