C++ const std::map reference fails to compile

不打扰是莪最后的温柔 提交于 2019-11-29 03:24:42

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.

When you're using operator[], std::map looks for item with given key. If it does not find any, it creates it. Hence the problem with const.

Use find method and you'll be fine.

Can you please post code on how you're trying to use find() ? The right way would be :

if( map.find(name) != map.end() )
{
   //...
}

If you're using C++11, std::map::at should work for you.

The reason std::map::operator[] doesn't work is that in the event of the key you're looking for not existing in the map, it will insert a new element using the provided key and return a reference to it (See the link for details). This is not possible on a const std::map.

The 'at' method, however, will throw an exception if the key doesn't exist. That being said, it is probably a good idea to check for the existence of the key using the std::map::find method before attempting to access the element using the 'at' method.

Probably because there is no const operator[] in std::map. operator[] will add the element you're looking for if it doesn't find it. Therefore, use the find() method if you want to search without the possibility of adding.

For your "const mismatched iterator errors" :

find() has two overloads:

      iterator find ( const key_type& x );
const_iterator find ( const key_type& x ) const;

My guess is that you're getting this error because you're doing something like assigning a non-const iterator (on the left) to the result of a find() call on a const map:

iterator<...> myIter /* non-const */ = myConstMap.find(...)

That would result in an error, though perhaps not the one you're seeing.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!