小编rol*_*and的帖子

通过[]运算符访问unordered_map时出现错误

我偶然发现了 unordered_map 的一个奇怪问题。

\n\n

首先,我生成了一条unordered_map<string, Person>记录(“Bob”,Person(1,“Bob”))并将其插入表中。然后我尝试使用带有键“Bob”的 [] 运算符来访问记录,但发生了错误。

\n\n

这是代码:

\n\n
#include<iostream>\n#include<unordered_map>\nusing namespace std;\n\nclass Person\n{\n    public:\n        int play;\n        string name;\n        Person(int p, string n):play(p), name(n) {}\n};\n\nint main()\n{\n    unordered_map<string,Person> test;\n    test.insert(std::make_pair("haha",Person(1,"haha")));\n    cout<<test["haha"].name<<endl;\n    return 0;\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

当我使用“g++ -S hash.cpp”编译代码时出现错误\n输出:

\n\n
In file included from /usr/include/c++/7/unordered_map:41:0,\n                 from hash.cpp:2:\n/usr/include/c++/7/tuple: In instantiation of \xe2\x80\x98std::pair<_T1, _T2>::pair(std::tuple<_Args1 ...>&, std::tuple<_Args2 ...>&, std::_Index_tuple<_Indexes1 ...>, std::_Index_tuple<_Indexes2 ...>) [with _Args1 = {std::__cxx11::basic_string<char, std::char_traits<char>, std::allocator<char> >&&}; long unsigned int ..._Indexes1 = {0}; _Args2 = {}; long unsigned int ..._Indexes2 = …
Run Code Online (Sandbox Code Playgroud)

c++ unordered-map g++ c++11

2
推荐指数
1
解决办法
3861
查看次数

标签 统计

c++ ×1

c++11 ×1

g++ ×1

unordered-map ×1