c++ - 如何编写比三值比较函数更整洁的 operator() 或 less-than-functor

标签 c++ stl

为结构编写运算符< () 似乎比编写经典的三值比较更清晰。

例如,对以下内容进行排序

struct S {
    int val;
};

你可以写一个运算符< ()

bool operator< ( const S &l, const S &r ) {
     return l.val < r.val;
}

或者,三值函数(通常采用以下方式)

int compare( const S &l, const S &r ) {
    if( r.val > l.val ) return 1;
    if( r.val < l.val ) return -1;
    return 0;
}

前者更清晰,因此可以说代码质量更好。 后者迫使您考虑 3 种情况,这会使代码复杂化。

但是这个想法在更复杂的结构中有点欺骗:

struct S {
    int x;
    int y;
};

下面写的很清楚,初学者往往这样写

bool operator< ( const S &l, const S &r ) {
     if( l.x < r.x ) return true;
     if( l.y < r.y ) return true;
     return false;
}

但这是错误的!你不能用这个正确排序!

这需要一些时间来思考 你实际上必须这样写

bool operator< ( const S &l, const S &r ) {
     if( l.x < r.x ) return true;
     if( l.x > r.x ) return false;
     if( l.y < r.y ) return true;
     if( l.y > r.y ) return false;
     return false;
}

让它正常工作。

您能以更好/更清晰的方式编写这种比较函数吗? 旧的三值比较函数至少“迫使”您考虑 >、< 和 == 情况。

最佳答案

如果我不关心性能或编译器涌出,我倾向于使用这个:

return make_tuple(l.x, l.y, ...) < make_tuple(r.x, r.y, ...);

对于拷贝版本来说稍微便宜一点:

return tie(cref(l.x), cref(l.y), ...) < tie(cref(r.x), cref(r.y), ...);

顺便说一句,第二个版本也适用于左值。

关于c++ - 如何编写比三值比较函数更整洁的 operator() 或 less-than-functor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3864948/

相关文章:

c++ - 转换字符串 vector : skip elements based on the previous value

c++ - 从输入文件中读取并存储在数组 C++ 中

c++ - 如何从 qml 启动一个 Qthread?

c++ - 保持插入顺序的 C+11 关联容器?

c++ - 访问嵌套的容器成员

c++ - 是否存在具有合理随机访问且从不调用元素类型的复制构造函数的 C++ 容器?

c++ - 可扩展的基类方法?

c++ new/delete 和 char *

c++ - 将枚举传递给构造函数

c++ - 定义 _HAS_TRADITIONAL_STL 以启用 STL 功能是否安全?