2011-12-28 57 views
1

私はGCCを使ってUbuntuでhash_map <という文字列、文字列、stringHashFunction> stringHashMapを定義します。私は文字列を文字列に変換する方法hash_map(文字列、文字列、stringHashFunction>をLinuxでC++

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

コンパイラレポートのバグを呼び出しhash_map正しく

中に文字列を使用している:

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

[]アクセッサはマップを変更できるため、非constにすることはできません。 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

3

stringHashから

を代わりにconst参照として格納/直接const又は通過のいずれかである見つける使用。 operator[]は、アイテムを挿入する必要がある可能性があるため、非const関数です。 constハッシュコンテナ内のアイテムを見つける必要がある場合は、findメソッドを使用してください。

関連する問題