Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

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 1 day ago by avibootz
...