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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

How to hash a set of GUIDs in C++

1 Answer

0 votes
#include <iostream>
#include <unordered_set>
#include <string>
#include <random>
#include <sstream>

// A GUID (Globally Unique Identifier) and a UUID (Universally Unique Identifier)
// are essentially the same, both being 128-bit values used to uniquely identify
// information in computer systems.

// Generate a UUIDv4 (random) 
std::string generate_uuid_v4() {
    static std::random_device rd;
    static std::mt19937_64 gen(rd());
    static std::uniform_int_distribution<uint64_t> dist;

    uint64_t part1 = dist(gen);
    uint64_t part2 = dist(gen);

    // Set version (4) and variant bits according to RFC 4122
    part2 = (part2 & 0x3FFFFFFFFFFFFFFF) | 0x8000000000000000; // variant
    part1 = (part1 & 0xFFFFFFFFFFFF0FFF) | 0x0000000000004000; // version 4

    std::stringstream ss;
    ss << std::hex;

    ss << ((part1 >> 32) & 0xFFFFFFFF)
       << "-"
       << ((part1 >> 16) & 0xFFFF)
       << "-"
       << (part1 & 0xFFFF)
       << "-"
       << ((part2 >> 48) & 0xFFFF)
       << "-"
       << (part2 & 0xFFFFFFFFFFFF);

    return ss.str();
}

int main() {

    // Create a set containing three randomly generated UUIDs.
    // generate_uuid_v4() produces a type‑4 GUID.
    std::unordered_set<std::string> guids = {
        generate_uuid_v4(),
        generate_uuid_v4(),
        generate_uuid_v4()
    };

    // Compute a hash value for the entire set.
    // std::hash is idiomatic C++ for hashing values.
    // We combine the hashes of all GUIDs in the set.
    std::size_t hash = 0;
    for (const auto& g : guids) {
        hash ^= std::hash<std::string>{}(g) + 0x9e3779b97f4a7c15ULL + (hash << 6) + (hash >> 2);
    }

    // Print the GUIDs so we can see what was hashed.
    std::cout << "GUIDs in the set:\n";
    for (const auto& g : guids) {
        std::cout << g << "\n";
    }

    // Print the resulting hash value.
    std::cout << "\nHash of the GUID set: " << hash << "\n";

    return 0;
}


/*
run:

GUIDs in the set:
261c0ca6-bb8e-47ec-9354-da3437db12cf
4c5dbb27-bd4b-46de-9941-8311de1dc6f6
d214f047-66c2-4a8e-b17e-23b426f7efef

Hash of the GUID set: 889325930297594684

*/

 



answered Jan 7 by avibootz
...