1
votes

I define a hash_map<string, string, stringHashFunction> stringHashMap in Ubuntu with GCC. And I promise that stringHashFunction is right, because I can use string to in hash_map correctly

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]

Why could this happen? How should I use string to string hashMap?

2

2 Answers

4
votes

[] 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/

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. Member function map::find does not produce this effect.

3
votes

stringHash is either directly const or passed/stored as a const reference. The operator[] is a non-const function because it may need to insert an item. If you need to find an item in a const hash container, just use the find method.