Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining == and < for structs with many data members

How to generalize the definition of < if the struct has arbitrarily many data members (< is to be defined using the order in which the data members are listed)? A simple example with 3 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;
    }
};

Using variadic templates and recursion somehow?

like image 941
prestokeys Avatar asked Dec 01 '22 16:12

prestokeys


2 Answers

You can use std::tie to create a tuple of references to the class members, and use the lexicographical 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);
}
like image 175
Mike Seymour Avatar answered Dec 25 '22 19:12

Mike Seymour


This structure scales easily, and allows using arbitrary comparison functions (e.g. 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;
like image 25
Ben Voigt Avatar answered Dec 25 '22 18:12

Ben Voigt