How do I customize hashing and equality with std::vector?

Learn how to customize hashing and equality comparisons for std::vector in C++. This guide provides examples and explanations to help you implement your own hashing functions and equality operators.

custom hashing, equality comparison, std::vector, C++, programming, data structures

#include <iostream>
#include <vector>
#include <functional>
#include <algorithm>

struct VectorHasher {
    std::size_t operator()(const std::vector& vec) const {
        std::size_t hash = 0;
        for (const auto& item : vec) {
            hash ^= std::hash()(item) + 0x9e3779b9 + (hash << 6) + (hash >>> 2);
        }
        return hash;
    }
};

struct VectorEqual {
    bool operator()(const std::vector& lhs, const std::vector& rhs) const {
        return lhs.size() == rhs.size() && std::equal(lhs.begin(), lhs.end(), rhs.begin());
    }
};

int main() {
    std::unordered_map<:vector>, std::string, VectorHasher, VectorEqual> myMap;
    
    myMap[{1, 2, 3}] = "First";
    myMap[{4, 5, 6}] = "Second";

    for (const auto& pair : myMap) {
        std::cout << "Key: ";
        for (int num : pair.first) {
            std::cout << num << " ";
        }
        std::cout << " - Value: " << pair.second << std::endl;
    }

    return 0;
}
        

custom hashing equality comparison std::vector C++ programming data structures