Sobes.tech
Junior — Middle

What conditions must be met to use an object as a key in an unordered_set container?

sobes.tech AI

Answer from AI

To use an object as a key for an unordered_set container in C++, the following conditions must be met:

  1. Define a hash function for this type. By default, unordered_set uses std::hash<T>. If there is no specialization of std::hash for your type, you need to write one or provide your own hash function.

  2. Define an equality operator (operator==) for your type, as unordered_set uses it to check for key equality.

Example:

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

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

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

std::unordered_set<MyKey> mySet;

Thus, the object must be hashable and comparable for equality.

What conditions must be met to use an object as a key… - sobes.tech