我有时会将小的structs
用作映射中的键,因此我必须为它们定义一个operator<
。通常,这看起来像这样:
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;
}
};
这似乎过于冗长且容易出错。是否有更好的方法或者某种可以自动定义 struct
或 class
的 operator<
的简单方法?我知道一些人喜欢使用像
memcmp(this, &rhs, sizeof(MyStruct)) < 0
这样的东西,但如果成员之间存在填充字节或者 char
字符串数组在 null 终止符后可能包含垃圾数据,则此方法可能无法正常工作。
return (a < rhs.a) || (a == rhs.a && ((b < rhs.b) || (b == rhs.b && c < rhs.c)));
- Jon Purdyif
子句实际上已经返回,所以不需要使用else
关键字。内部代码块也是如此。在这两种情况下,你可以直接省略else
这个单词。 - Andrew Truckle