I have a struct of following type which I am planning use as a key in a map.
Hence I write a comparator like below. I would like to know if there is a more elegant yet efficient way of doing this.
May be using std::pair or something.
struct T
{
int a, b, c, d;
bool operator< (const T& r) {
if (a < r.a)
return true
else if (a == r.a)
if (b < r.b)
return true;
else if (b == r.b)
if (c < r.c)
return true;
else if (c == r.c)
if (d < r.d)
return true;
return false;
}
}
Can you use C++11? If so:
struct T {
int a, b, c, d;
bool operator<(const T& rhs) const {
return tied() < rhs.tied();
}
private:
std::tuple<int, int, int, int> tied() const {
return std::make_tuple(a, b, c, d);
}
};
Alternatively, I would prefer returning at each possible opportunity to avoid the error-prone awkward nesting approach:
bool operator<(const T& rhs) const {
if (a != rhs.a) return a < rhs.a;
if (b != rhs.b) return b < rhs.b;
if (c != rhs.c) return c < rhs.c;
return d < rhs.d;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With