C++11 C++;:从另一个映射检索STL映射时出错

C++11 C++;:从另一个映射检索STL映射时出错,c++11,stl,C++11,Stl,我有以下代码- #include <map> using Type1 = std::map<std::string, unsigned long long>; using Type2 = std::map<std::string, Type1>; class T { private: Type2 mymap; public: const Type1& get(const std::string& key

我有以下代码-

#include <map>

using Type1 = std::map<std::string, unsigned long long>;
using Type2 = std::map<std::string, Type1>;

class T
{
   private:
      Type2 mymap;

   public:
      const Type1& get(const std::string& key) const;
};

const Type1& T::get(const std::string& key) const
{
   return mymap[key];
}

int main(void)
{
}
#包括
使用Type1=std::map;
使用Type2=std::map;
T类
{
私人:
2型mymap;
公众:
consttype1&get(conststd::string&key)const;
};
常量Type1&T::get(常量std::string&key)常量
{
返回mymap[key];
}
内部主(空)
{
}
这不会编译,编译器会抱怨-

maps.cpp:在成员函数“consttype1&T::get(conststring&)”中
const':maps.cpp:17:20:错误:传递“consttype2{aka const”
std::map}作为'std::map::mapped_type&std::map::operator[](const key_type&)[with _key=std::basic_string;_Tp=std::map;_Compare=std::less;
_Alloc=std::分配器;
标准::映射::映射的类型=
标准::地图;
标准::映射::键类型=
std::basic_string]'丢弃限定符[-fppermissive]
返回mymap[key];
^
我需要帮助理解这个错误。据我所知,我没有修改get函数中的“this”


谢谢

错误来自以下事实: 可以 如果该键不存在,则插入该键


您可以先执行
std::map::find
作为检查。

错误来自以下事实: 可以 如果该键不存在,则插入该键


您可以先执行
std::map::find
作为检查。

map
操作符[]
可能会修改映射(如果键不存在,则插入一个空白条目),因此您不能在
常量
成员函数中使用它。您可以将函数设为非常量,或者改用
map::find
(如果映射中不存在条目,则引发异常)@M.M谢谢!我现在明白了。
map
操作符[]
可以修改映射(如果密钥不存在,则插入空白条目),因此您不能在
const
成员函数中使用它。您可以将函数设为非const,或者改用
map::find
(如果映射中不存在该项,则引发异常)@M.M谢谢!我现在明白了。我总是建议使用
count
而不是
find
,因为我发现它理解起来比较短。无论如何,也可以使用
at
代替
操作符[]
如果密钥不存在,将引发异常。我始终建议使用
count
而不是
find
,因为我发现它较难理解。无论如何,也可以使用
at
代替
操作符[]
,如果密钥不存在,将引发异常。
maps.cpp: In member function ‘const Type1& T::get(const string&)
const’: maps.cpp:17:20: error: passing ‘const Type2 {aka const
std::map<std::basic_string<char>, std::map<std::basic_string<char>,
long long unsigned int> >}’ as ‘this’ argument of ‘std::map<_Key, _Tp,
_Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::basic_string<char>; _Tp = std::map<std::basic_string<char>, long
long unsigned int>; _Compare = std::less<std::basic_string<char> >;
_Alloc = std::allocator<std::pair<const std::basic_string<char>, std::map<std::basic_string<char>, long long unsigned int> > >;
std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type =
std::map<std::basic_string<char>, long long unsigned int>;
std::map<_Key, _Tp, _Compare, _Alloc>::key_type =
std::basic_string<char>]’ discards qualifiers [-fpermissive]
return mymap[key];
                ^