Sriram Subramanian
Sriram Subramanian

Reputation: 2753

Does std::string need a hash function when used with unordered_sets?

I am using an unordered set of std::strings. What is the recommended way to specify the hash function for it? Currently it is using the default. Do I need to specify one explicitly which could perform better?

Upvotes: 1

Views: 713

Answers (4)

Roman Kutlak
Roman Kutlak

Reputation: 2784

I still haven't figured out how to add the little comment under an answer...I would prefer to post this under Michael Burr's answer. Anyway, c++11 has std::hash<string> as a part of the library. Here you can view all the supported hash functions.

Upvotes: 0

user677656
user677656

Reputation:

You could check the wiki , where you can see that in order to specify the hash function you should write something like :

 std::unordered_map<X,int,hash_X> my_map;

where hash_X is the definition of the hash function.

For completeness I include the code of the definition found in the wiki

struct X{int i,j,k;};

struct hash_X{
  size_t operator()(const X &x){
    return hash<int>()(x.i) ^ hash<int>()(x.j) ^ hash<int>()(x.k);
  }
};

Upvotes: 0

Ken Wayne VanderLinde
Ken Wayne VanderLinde

Reputation: 19347

The standard specialization for std::string is probably good enough (probably even extremely good) for strings in general. But if your working with string of a very specific format, you probably could find or design a better algorithm for your particular case.

Upvotes: 1

Michael Burr
Michael Burr

Reputation: 340516

There's no need to provide your own. If you're using VS 2010 the hash function for std::string is in the xfunctional header file included by <functional> if you want to take a look for yourself about whether it would meet your needs:

template<>
    class hash<_STD string>
// ...

Upvotes: 0

Related Questions