Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why std::hash<int> seems to be identity function

#include <iostream>

int main() {
    std::hash<int> hash_f;
    std::cout << hash_f(0) << std::endl;
    std::cout << hash_f(1) << std::endl;
    std::cout << hash_f(2) << std::endl;
    std::cout << hash_f(3) << std::endl;
}

I compile with "g++ main.cpp -std=c++11" and then the result is :

0
1
2
3

Why is this happening? I don't use any library and I don't have a specialized hashing function.

Addendum : I wanted to define the hash for an unordered_set of unordered_set of int with the hash of a set being the sum of its components hashs, but if it's just identity it's not cool because the hash of {2,4} is the same than the hash of {1,5}. The simplest way to avoid that is may be to use the std::hash double function.

like image 412
François Avatar asked Jul 11 '16 10:07

François


People also ask

Is the identity function a universal hash function?

But the identity function is usually not considered a hash function.

What is STD hash function?

The hash class is default constructible, which means that one can construct this object without any arguments or initialization values. It is used to get the hash value of the argument that is being passed to it. If the argument doesn't change, the value doesn't change either.

What is hash function in C++?

A Hash Table in C/C++ (Associative array) is a data structure that maps keys to values. This uses a hash function to compute indexes for a key. Based on the Hash Table index, we can store the value at the appropriate location.

Is STD hash unique?

Yes, std::hash return same result for different std::string . The creation of buckets is different by different compiler.


1 Answers

It seems its identity, its allowed as its distinct.. From cpp reference

The actual hash functions are implementation-dependent and are not required to fulfill any other quality criteria except those specified above. Notably, some implementations use trivial (identity) hash functions which map an integer to itself. In other words, these hash functions are designed to work with unordered associative containers, but not as cryptographic hashes, for example. ....

like image 83
nayana Avatar answered Sep 20 '22 17:09

nayana