Definition == and <for structures with many data elements

How to generalize the definition of <if the structure has an arbitrarily many data members (<is determined by the order in which the data members are listed)? A simple example with three data members:

struct nData {
    int a;
    double b;
    CustomClass c;   // with == and < defined for CustomClass
    bool operator == (const nData& other) {return (a == other.a) && (b == other.b) && (c == other.c);}
    bool operator < (const nData& other) {
        if (  (a < other.a)  ||  ((a == other.a) && (b < other.b))  ||
                ((a == other.a) && (b == other.b) && (c < other.c))  )
            return true;
        return false;
    }
};

How to use variable patterns and recursion?

+4
source share
2 answers

You can use std::tielinks to class members to create a tuple and use the lexicographic comparison operators defined for tuples:

bool operator < (const nData& other) const {  // better make it const
    return std::tie(a,b,c) < std::tie(other.a, other.b, other.c);
}
+15
source

(, strcmp)

if (a != other.a) return a < other.a;
if (b != other.b) return b < other.b;
if (c != other.c) return c < other.c;
return false;
+3

Source: https://habr.com/ru/post/1527349/


All Articles