2011-12-28 57 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方法。

相關問題