using-gcc-c-hash-classes-with-strings

So even though hash_map and hash_set aren’t a part of the C++ standard, there are still implementations included with the gcc compiler. You have to include or and a little magic to get them to work properly with std::string keys.

// Example code using a hash_set with std::string keys on gcc
// Example based on hash_set code from "6.7 Using Hashed Containers"
// in O'Reilly C++ Cookbook by Stephens, Diggins, Turkanis & Cogswell  (2006)
// and gcc fix from post http://gcc.gnu.org/ml/libstdc++/2002-04/msg00107.html
// Tested with g++ 4.1.2
// Compile with:
// g++ -o hash hash.cpp
// Kristi Tsukida <kristi.tsukida at gmail dot com> 30-10-2008
 
#include <iostream>
#include <string>
#include <ext/hash_set>
 
using namespace std;
// The __gnu_cxx namespace contains the hash_set since it's not standard c++
using namespace __gnu_cxx;
 
// This is the magic that will allow the usage of string keys in the hash
namespace __gnu_cxx
{
        template<> struct hash< std::string >
        {
                size_t operator()( const std::string& x ) const
                {
                        return hash< const char* >()( x.c_str() );
                }
        };
}
 
// must specify the hash<string> hash function
typedef hash_set<string, hash<string> > string_hash_set;
 
int main()
{
	string_hash_set hs;
 
	string s = "bravo";
	hs.insert(s);
	s = "alpha";
	hs.insert(s);
	s = "charlie";
	hs.insert(s);
 
	for(string_hash_set::const_iterator p = hs.begin(); p!= hs.end(); ++p)
	{
		cout << *p << endl;
	}
 
}