How to define operator<
on n-tuple (for example on 3-tuple) so that it satisfy strict weak ordering concept ? I know that boost library has
...a new answer to a very old question, but the existing answer miss the easy solution from C++11...
C++11 onwards provides std::tupletuple
s have a matching operator< that initially compares the left-most element, then works along the tuple until the outcome's clear. That's suitable for providing the strict weak ordering expected by e.g. std::set and std::map.
If you have data in some other variables (e.g. fields in a struct
), you can even use std::tie() to creates a tuple of references, which can then be compared to another such tuple. That makes it easy to write operator<
for specific member-data fields in a user-defined class
/struct
type:
struct My_Struct
{
int a_;
double b_;
std::string c_;
};
bool operator<(const My_Struct& lhs, const My_Struct& rhs)
{
return std::tie(lhs.a_, lhs.b_, lhs.c_) < std::tie(rhs.a_, rhs.b_, rhs.c_);
}