2011-12-28 75 views
1

我定义了一个hash_map <在GCC中的字符串,字符串,stringHashFunction> stringHashMap我保证stringHashFunction是正确的,因为我可以在正确的hash_map如何使用字符串字符串hash_map(hash_map <string,string,stringHashFunction>在Linux C++

当我打电话

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

编译器bug报告使用字符串到:

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]

为什么这可能发生?我应该如何使用字符串来字符串hashMap?

回答

4

[]访问者可以修改地图,因此它不能是非常量。使用找到代替

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.

+0

非常感谢。确实是这个问题 – RandyTek 2011-12-28 06:40:10

3

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

相关问题