Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::hash — function object for hashing keys

std::hash<Key> maps a key to a std::size_t value and is the default hasher for unordered associative containers. Equal keys must have equal hashes, but equal hashes do not prove that the keys are equal.

Version: C++23; repository compiler flag, production runtime not attested

Syntax

#include <cstddef>
#include <functional>
std::hash<Key> hasher;
std::size_t value = hasher(key);

std::hash is a class template declared in <functional>. An enabled specialization std::hash<Key> provides a function object: hasher(key) returns std::size_t. Unordered associative containers use it as their default hasher.

If k1 == k2, then hasher(k1) == hasher(k2) must hold. The reverse does not hold: different keys can cause collisions. A hash therefore does not replace key comparison. The result for the same value must remain constant within one execution of the program; do not assume it matches across executions or implementations. Do not store it as a persistent identifier.

The standard provides enabled specializations for, among others, cv-unqualified arithmetic, enumeration, and pointer types. If neither the library nor the program supplies a specialization for Key, std::hash<Key> is disabled and cannot be used as a hasher. Merely defining a custom type does not automatically provide hashing for it.

The example compares hashes of equal integers instead of printing a nonportable numeric hash value. The expected result is true.

Examples

#include <functional>
#include <iostream>

int main() {
    const std::hash<int> hasher{};
    const int a = 42;
    const int b = 42;
    std::cout << std::boolalpha << (hasher(a) == hasher(b)) << '\n';
}

Result

true

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources