timakro timakro - 1 month ago 9
C++ Question

Lower than operator for structs

I've got a struct containing two data types that have the lower than, greater than and equals operators implemented. I want to implement the lower than operator for my struct:

struct number_pair
{
int a;
int b;
bool operator<(const pair& other) const { return ?; }
}


You need to be able to sort multiple instances of the struct using the operator. The order should respect both
a
and
b
. I don't want to use libraries other than
std
and I'm on C++98 so
std::tuple
is not available.

Is it possible to achieve what I want if the two data types only have the lower than, greater than and equals operators implemented? If thats the case, how would the implementation of the operator look, and otherwise, what else would you need to know about the data types to implement the operator?

Answer

You want lexicographical comparison. There's a C++ function for this: std::lexicographical_compare. This algorithm is the same one that's used for sorting std::tuple objects.

You can easily implement this yourself (without std::lexicographical_compare) like so:

struct pair {
    int a;
    int b;
    bool operator<(const pair& other) const {
        return a < other.a || (a == other.a && b < other.b);
    }
};

Alternatively, you can use std::pair<int, int> to do this. It's already got a lexicographical-order operator< defined.

Comments