I sometimes use small structs
as keys in maps, and so I have to define an operator<
for them. Usually, this ends up looking something like this:
struct MyStruct
{
int a;
int b;
int c;
bool operator<(const MyStruct& rhs) const
{
if (a < rhs.a)
{
return true;
}
else if (a == rhs.a)
{
if (b < rhs.b)
{
return true;
}
else if (b == rhs.b)
{
return c < rhs.c;
}
}
return false;
}
};
This seems awfully verbose and error-prone. Is there a better way, or some easy way to automate definition of operator<
for a struct
or class
?
I know some people like to just use something like memcmp(this, &rhs, sizeof(MyStruct)) < 0
, but this may not work correctly if there are padding bytes between the members, or if there are char
string arrays that may contain garbage after the null terminators.