This is the mail archive of the
libstdc++@gcc.gnu.org
mailing list for the libstdc++ project.
Re: hash<string> and third-party libraries
- From: Brad Spencer <spencer at infointeractive dot com>
- To: Daniel Kegel <dank at kegel dot com>
- Cc: libstdc++ at gcc dot gnu dot org
- Date: Fri, 7 May 2004 10:26:19 -0300
- Subject: Re: hash<string> and third-party libraries
- References: <409A9CCF.90403@kegel.com>
On Thu, May 06, 2004 at 01:15:11PM -0700, Daniel Kegel wrote:
> libstdc++ includes handy extensions like hash_map and hash_set.
> Although using them is inherently non-portable,
> one might reasonably expect their use to be portable amongst all
> people using the same version of libstdc++. However, if you want to use
> C++ strings as hash keys, you have to supply your own definition
> of hash<string>, e.g.
>
> namespace __gnu_cxx {
> template<> struct hash< std::string > {
> size_t operator()( const std::string& x ) const
> {
> return hash< const char* >()( x.c_str() );
> }
> };
> }
You can use the second template argument of hash_set (or the third
template argument of hash_map).
struct GenericStringHash
{
size_t operator()(const std::string &id) const
{
const std::string::size_type size = id.size();
size_t h = 0;
for(std::string::size_type i = 0; i < size; i++) {
h = 5 * h + id[i];
}
return h;
}
};
typedef __gnu_cxx::hash_map<std::string, SomethingElse,
GenericStringHash> Index;
Then, you won't conflict with anyone else's definitions of functions
they (ill-advisedly) placed into the __gnu_cxx (or std) namespaces.
--
------------------------------------------------------------------
Brad Spencer - spencer@infointeractive.com - "It's quite nice..."
Systems Architect | InfoInterActive Corp. | A Canadian AOL Company