How to hash a string in C++

1 Answer

0 votes
#include <functional> // std::hash
#include <iostream>
#include <string>

/*
    Computes a hash value for a string.

    std::hash is the standard C++ hashing facility. It is commonly
    used by containers such as std::unordered_map and std::unordered_set.

    Important notes:
    - The same input produces the same hash value within a given implementation.
    - Different strings can produce the same hash value (a collision).
    - Hashes are intended for fast lookups, not for security.
    - Do not use std::hash for password storage or encryption.
*/
std::size_t hashString(const std::string& text)
{
    std::hash<std::string> hasher;
    
    return hasher(text);
}

int main()
{
    // The string we want to hash.
    const std::string text{"Hello, World!"};

    // Compute the hash value.
    const std::size_t hashValue = hashString(text);

    std::cout << "Original string: " << text << '\n';
    std::cout << "Hash value     : " << hashValue << '\n';

    /*
        Example comparison:

        Rather than comparing long strings repeatedly, many data
        structures first compare hash values because comparing
        integers is typically faster.

        However, a matching hash does not guarantee that two
        strings are equal because collisions are possible.
        Therefore, when an exact match is required, compare
        the original strings as well.
    */

    const std::string anotherText{"Hello, World!"};

    if (hashString(text) == hashString(anotherText))
    {
        std::cout << "Hashes match.\n";

        // Verify the actual strings to guard against collisions.
        if (text == anotherText) {
            std::cout << "Strings are identical.\n";
        }
    }
}


/*
run:

Original string: Hello, World!
Hash value     : 18371290486108036847
Hashes match.
Strings are identical.

*/

 



answered Oct 4 by avibootz
...