SGI の hash_map で std::string をキーにする
元々 SGI の map 実装である hash_map ですが、std::string をキーにしようとするとコンパイルが通りません。
手元の coLinux(Linux debian 2.6.17-co-0.8.0 #1 PREEMPT Sun Jul 8 14:00:12 CEST 2007 i686 GNU/Linux)、gcc 4.1.2 な環境で、以下の test.cc だと、
-
#include <string>
-
#include <ext/hash_map>
-
-
using namespace std;
-
-
int main(int argc, char* argv[]) {
-
__gnu_cxx::hash_map<string, int> m;
-
}
は g++ test.cc でコンパイルできますが、1 行追加して(以下の 8 行目)、
-
#include <string>
-
#include <ext/hash_map>
-
-
using namespace std;
-
-
int main(int argc, char* argv[]) {
-
__gnu_cxx::hash_map<string, int> m;
-
__gnu_cxx::hash_map<string, int>::iterator it = m.find("hoge");
-
}
は怒られます。 Tip about STL hash_map and string にもありますが、その実装が std::string をキーとすることを想定していないのが原因。具体的には、この環境だと /usr/include/c++/4.1.2/ext/hash_fun.h に定義がありますが、std::string な値に対してをハッシュ値を計算する実装がありません。なので、それを追加してやって(以下の 6 ~ 15 行目)、
-
#include <string>
-
#include <ext/hash_map>
-
-
using namespace std;
-
-
namespace __gnu_cxx {
-
template<> struct hash<std::string> {
-
size_t operator()(const std::string& x) const {
-
return hash<const char*>()(x.c_str());
-
}
-
};
-
}
-
-
int main(int argc, char* argv[]) {
-
__gnu_cxx::hash_map<string, int> m;
-
__gnu_cxx::hash_map<string, int>::iterator it = m.find("hoge");
-
}
であれば無事コンパイルが通るよという話でした。
なんつうネタはちょっと探してみればいくらでもありますね。テヘ。

No comments
Jump to comment form | comments rss [?] | trackback uri [?]