【发布时间】:2011-04-22 09:36:30
【问题描述】:
我有时使用小的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 字符串数组在空终止符之后可能包含垃圾,这可能无法正常工作。
【问题讨论】:
-
您可以简洁明了,不会更容易出错:
return (a < rhs.a || (a == rhs.a && (b < rhs.b || (b == rhs.b && c < rhs.c))));