C++ 11 – Hashing

For hashing, two types of features were introduced in C++ 11.

std::hash was introduced, which can calculate the hash for a specific element such as int, string, or other data types.

std::unordered_mapstd::unordered_setstd::unordered_multimapstd::unordered_multiset are introduced in STLs. These containers are introduced in C++ 11, and these are unordered versions of map, set, multimap, and multiset.

These containers use internally hash-based utilities such as std::hash and std::equal_to internally and are based on hashing techniques.

Below is a sample program using std::hash. The program can be downloaded at https://github.com/codeversionmaster/cplusplus/blob/cplusplus17/hashing.cpp.

$ cat hashing.cpp 
#include <iostream>
#include <string>
#include <functional>

int main() {
    std::hash<int> int_hash;
    int num = 21;
    std::size_t num_hash = int_hash(num);
    std::cout << "Hash value for " << num << " is: " << num_hash << std::endl;

    std::hash<std::string> string_hash;
    std::string word = "hello";
    std::size_t word_hash = string_hash(word);
    std::cout << "Hash value for \"" << word << "\" is: " << word_hash << std::endl;

    return 0;
}

You can compile and run the program below to see the output.

$ g++ -std=c++11 -o hashing hashing.cpp 
$ ./hashing 
Hash value for 21 is: 21
Hash value for "hello" is: 2762169579135187400