Low*_*eek 4 c++ coding-style indentation
在工作中,我最近为从已发布的规范实现的类编写了一个小于运算符,该类具有许多属性,其中六个用于唯一标识类的实例.(为了这个问题,我们将这些属性称为af.)此外,这六个属性有六种不同的类型.我将运算符定义为:
bool operator<(const Class& lhs, const Class& rhs)
{
bool retval = (&lhs != &rhs);
if (retval == true)
{
if (lhs.a == rhs.a)
{
if (lhs.b == rhs.b)
{
if (lhs.c == rhs.c)
{
if (lhs.d == rhs.d)
{
if (lhs.e == rhs.e)
{
retval = (lhs.f < rhs.f);
} else {
retval = (lhs.e < rhs.e);
}
} else {
retval = (lhs.d < rhs.d);
}
} else {
retval = (lhs.c < rhs.c);
}
} else {
retval = (lhs.b < rhs.b);
}
} else {
retval = (lhs.a < rhs.a);
}
}
return retval;
}
Run Code Online (Sandbox Code Playgroud)
当然,这打破了Linux内核编码的理念,"如果你需要3级以上的缩进,那么你无论如何都要搞砸了,应该修复你的程序." 所以我的问题是,是否有更好的方法来定义此运算符,以便没有这么多级别的缩进?
Bri*_*ian 11
您可以像这样编写这种词典比较:
if (lhs.a != rhs.a) return lhs.a < rhs.a;
if (lhs.b != rhs.b) return lhs.b < rhs.b;
if (lhs.c != rhs.c) return lhs.c < rhs.c;
if (lhs.d != rhs.d) return lhs.d < rhs.d;
if (lhs.e != rhs.e) return lhs.e < rhs.e;
return lhs.f < rhs.f;
Run Code Online (Sandbox Code Playgroud)
您可以使用以下单个返回重写此内容:
bool result;
if (lhs.a != rhs.a) result = lhs.a < rhs.a;
else if (lhs.b != rhs.b) result = lhs.b < rhs.b;
else if (lhs.c != rhs.c) result = lhs.c < rhs.c;
else if (lhs.d != rhs.d) result = lhs.d < rhs.d;
else if (lhs.e != rhs.e) result = lhs.e < rhs.e;
else result = lhs.f < rhs.f;
return result;
Run Code Online (Sandbox Code Playgroud)
Chr*_*rew 11
您可以使用std::tie词典比较:
bool operator<(const Class& lhs, const Class& r) {
return std::tie(lhs.a, lhs.b, lhs.c, lhs.d, lhs.e) < std::tie(rhs.a, rhs.b, rhs.c, rhs.d, rhs.e);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
479 次 |
| 最近记录: |