user1056903 user1056903 - 25 days ago 6
C++ Question

Implementing the '<' operator

What is the correct way to implement the '<' operator for using the following simple class as a key in a

std::map
(functions are omitted)?

class Person
{
public:
bool valid = false;
std::string name = "";
std::string id = "";
}

Answer

You could use std::tie.

class Person
{
public:
    bool valid = false;
    std::string name = "";
    std::string id = "";

    bool operator<(const Person& r) const
    {
        return std::tie(valid, name, id) < std::tie(r.valid, r.name, r.id);
    }
}

Explanation:

std::tie(xs...) creates an std::tuple of references to the passed xs... arguments. Comparison between two std::tuple instances works by lexicographically comparing the elements, thus providing an ordering for your type.

More information here on cppsamples and in this question.