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

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

本文关键字:map string 字符串 hash Linux stringHashFunction gt lt C++      更新时间:2023-10-16

我定义了一个hash_map<string,> stringHashMap在Ubuntu与GCC。我保证stringHashFunction是正确的,因为我可以在hash_map中正确使用string to

当我呼叫

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

编译器报告错误:

错误:传递' const __gnu_cxx::hash_map, std::basic_string, StringHashFunctionStruct> '作为' this '参数' _t&__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] '放弃限定符[-fpermissive]

为什么会发生这种情况?我应该如何使用字符串到字符串的hashMap?

[] accessor可以修改map,因此不能是非const。用find代替

从http://www.cplusplus.com/reference/stl/map/operator%5B%5D/

注意最后一次访问(对元素'd')是如何插入一个新元素的使用该键映射并初始化为其默认值(一个空的字符串),即使访问它只是为了检索它的值。成员函数map::find不会产生此效果。

stringHash要么直接是const,要么作为const引用传递/存储。operator[]是非const函数,因为它可能需要插入一个项。如果需要在const散列容器中查找项,只需使用find方法。