简体   繁体   English

如何使用字符串将hash_map(hash_map <string, string, stringHashFunction> 在Linux C ++中

[英]How to use string to string hash_map(hash_map<string, string, stringHashFunction> in Linux C++

I define a hash_map<string, string, stringHashFunction> stringHashMap in Ubuntu with GCC. 我在带有GCC的Ubuntu中定义了hash_map <string,string,stringHashFunction> stringHashMap。 And I promise that stringHashFunction is right, because I can use string to in hash_map correctly 我保证stringHashFunction是正确的,因为我可以在hash_map中正确使用字符串

When I call 当我打电话

string a = "sgsg";
string temp = stringHash[a];

the compiler report bugs that: 编译器报告以下错误:

error: passing 'const __gnu_cxx::hash_map, std::basic_string, StringHashFunctionStruct>' as 'this' argument of '_Tp& __gnu_cxx::hash_map<_Key, _Tp, _HashFn, _EqualKey, _Alloc>::operator[](const key_type&) [with _Key = std::basic_string, _Tp = std::basic_string, _HashFn = StringHashFunctionStruct, _EqualKey = std::equal_to >, _Alloc = std::allocator >, __gnu_cxx::hash_map<_Key, _Tp, _HashFn, _EqualKey, _Alloc>::key_type = std::basic_string]' discards qualifiers [-fpermissive] 错误:将'const __gnu_cxx :: hash_map,std :: basic_string,StringHashFunctionStruct>'作为'_Tp&__gnu_cxx :: hash_map <_Key,_Tp,_HashFn,_EqualKey,_Alloc>:_ operator [](const key)的'this'参数传递[带有_Key = std :: basic_string,_Tp = std :: basic_string,_HashFn = StringHashFunctionStruct,_EqualKey = std :: equal_to>,_ Alloc = std :: allocator>,__ gnu_cxx :: hash_map <_Key,_Tp,_ > :: key_type = std :: basic_string]'丢弃限定词[-fpermissive]

Why could this happen? 为什么会发生这种情况? How should I use string to string hashMap? 如何使用字符串将hashMap字符串化?

[] accessor can modify the map, hence it can't be non-const. []访问者可以修改地图,因此它不能是非常量的。 use find instead 使用查找代替

from http://www.cplusplus.com/reference/stl/map/operator%5B%5D/ 来自http://www.cplusplus.com/reference/stl/map/operator%5B%5D/

Notice how the last access (to element 'd') inserts a new element in the map with that key and initialized to its default value (an empty string) even though it is accessed only to retrieve its value. 请注意,最后一次访问(对元素“ d”)如何使用该键在映射中插入新元素,并初始化为其默认值(空字符串),即使仅通过访问来检索其值也是如此。 Member function map::find does not produce this effect. 成员函数map :: find不会产生这种效果。

stringHash is either directly const or passed/stored as a const reference. stringHash是直接const或作为const引用传递/存储。 The operator[] is a non-const function because it may need to insert an item. operator[]是一个非常量函数,因为它可能需要插入一个项目。 If you need to find an item in a const hash container, just use the find method. 如果需要在const哈希容器中查找项目,只需使用find方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM