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
{
A a;
B b;
C 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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…