Sobes.tech
Junior — Middle

What conditions must be met to use a certain type as a key in an std::unordered_map container?

sobes.tech AI

Answer from AI

To use a specific type as a key in a std::unordered_map container in C++, the following must be defined for that type:

  1. Hash function — a function that takes a key and returns a std::size_t hash value. By default, std::hash<T> is used. If there is no specialization of std::hash for your type T, you need to define one.

  2. Equality operatoroperator==, which compares two keys for equality. It is needed to resolve hash collisions.

Example for a user-defined type:

struct Key {
    int id;
    std::string name;

    bool operator==(const Key& other) const {
        return id == other.id && name == other.name;
    }
};

namespace std {
    template<>
    struct hash<Key> {
        std::size_t operator()(const Key& k) const {
            return std::hash<int>()(k.id) ^ (std::hash<std::string>()(k.name) << 1);
        }
    };
}

std::unordered_map<Key, Value> myMap;

Without these conditions, the compiler will produce an error when attempting to use the type as a key in std::unordered_map.

What conditions must be met to use a certain type as… - sobes.tech