Sobes.tech
Junior — Middle

What properties should a class have to be used as a unique identifier or key in collections?

sobes.tech AI

Answer from AI

To use a class instance as a unique identifier or key in collections (for example, in std::unordered_map or std::map), the class must provide:

  1. Equality comparison operator (operator==) — to check if two objects are equal.
  2. Order comparison operator (operator<) — if using std::map or other ordered containers.
  3. Hash function — if using std::unordered_map or std::unordered_set. You can specialize the std::hash template for your class.

Example for use in std::unordered_map:

#include <string>
#include <unordered_map>

class MyKey {
public:
    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);
        }
    };
}

int main() {
    std::unordered_map<MyKey, int> map;
    map[{1, "test"}] = 42;
}

Thus, the class must be comparable and have a correct hash for use as a key.