Sobes.tech
Junior — Middle

What conditions must be met for an object to serve as a key in a std::map container?

sobes.tech AI

Answer from AI

For an object to serve as a key in a std::map container, it must have a defined strict ordering. By default, std::map uses the < operator to compare keys. This means your type must support the < operator or you must provide a custom comparator that implements a strict weak ordering.

Main conditions:

  • The key must be copyable or movable.
  • The key must have a defined < operator or a comparator that establishes a strict weak order.

Example with a user-defined type and comparator:

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

struct MyKeyCompare {
    bool operator()(const MyKey& lhs, const MyKey& rhs) const {
        if (lhs.id != rhs.id) return lhs.id < rhs.id;
        return lhs.name < rhs.name;
    }
};

std::map<MyKey, int, MyKeyCompare> myMap;

If the < operator is defined for the type, you can use std::map<MyKey, ValueType> without an additional comparator.