jeudi 1 septembre 2016

Hashing a string and an int together?

I have to write a hash function, so that I can place a std::pair<int,std::string> in a unordered_set.

Regarding the input:

  1. The strings that will be hashed are very small (1-3 letters in length).
  2. Likewise, the integers will be unsigned numbers which are small (much smaller than the limit of unsigned int).

Does it make sense to use the hash of the string (as a number), and just use Cantor's enumeration of pairs to generate a "new" hash?

Since the "built-in" hash function for std::string should be a decent hash function...

    struct intStringHash{
    public:
        inline std::size_t operator()(const std::pair<int,std::string>&c)const{
            int x = c.first;
            std::string s = c.second;
            std::hash<std::string> stringHash;
            int y = stringHash(s);

            return ((x+y)*(x+y+1)/2 + y); // Cantor's enumeration of pairs
        }
    };

Aucun commentaire:

Enregistrer un commentaire