Articles

Use custom class as C++ map key

In howto on Jul 5, 2016 by theoryl Tagged: ,

To be able to use a custom class as the key in C++ std::map, a less-than operator (operator<) must be defined for the custom class. One way is to define it in the class itself:

class MyClass{
public:
    MyClass(int x, int y) : _x(x), _y(y) {}
    ~MyClass() {}

    bool operator<(const MyClass& other) const{
        return (_x < other._x) || (!(other._x < _x) && (_y < other._y));
    }

private:
    int _x, _y;
};

Alternatively, one can define a comparison function (in the global scope):

class MyClass{
public:
    MyClass(int x, int y) : _x(x), _y(y) {}
    ~MyClass() {}

    double x() const { return _x; }
    double y() const { return _y; }

private:
    int _x, _y;
};

bool operator<(const MyClass& lhs, const MyClass& rhs) {
    return (lhs.x() < rhs.x()) || (!(rhs.x() < lhs.x()) && (lhs.y() < rhs.y()));
}

Or, define a comparison functor (this is probably the recommended way):

class MyClass{
public:
    MyClass(int x, int y) : _x(x), _y(y) {}
    ~MyClass() {}

    double x() const { return _x; }
    double y() const { return _y; }

private:
    int _x, _y;
};

struct MyComparator {
    // use it like std::map<MyClass, int, MyComparator>
    bool operator()(const MyClass& lhs, const MyClass& rhs) const {
        return (lhs.x() < rhs.x()) || (!(rhs.x() < lhs.x()) && (lhs.y() < rhs.y()));
    }
};

Note that std::map decides two keys are equal if (!(key1 < key2) && !(key2 < key1)).

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: