This is the mail archive of the libstdc++@gcc.gnu.org mailing list for the libstdc++ project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: hash<string> and third-party libraries


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


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]