在 c++ 中重载小于运算符以用于 std::sort

Overloading less than operator in c++ for use in std::sort

我有一个这样定义的结构:

struct IFSFunc {
    int a;

    bool operator<(const IFSFunc& other) {
        return a < other.a;
    }
};

因为 IFSfuncstructoperator< 的访问修饰符应该是 public.

我也有这个代码:

#include <algorithm>
std::vector<std::pair<double, IFSFunc>> ifsFuncs;

// fill the vector with various data

std::sort(ifsFuncs.begin(), ifsFuncs.end());

我需要根据对中的第一个 double 对 ifsFuncs 进行排序。我不关心 IFSFunc 结构,如果 double 相同。

但是,要使 std::sort 起作用,其定义如下:

template <class _Ty1, class _Ty2>
_NODISCARD constexpr bool operator<(const pair<_Ty1, _Ty2>& _Left, const pair<_Ty1, _Ty2>& _Right) {
    return _Left.first < _Right.first || (!(_Right.first < _Left.first) && _Left.second < _Right.second);
}

在本例 IFSfunc 中,我必须覆盖 second 的小于运算符,我确实这样做了。但是,尝试编译此代码会出现以下错误:

Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const _Ty2' (or there is no acceptable conversion)

为什么?

我刚刚弄明白了。重载函数签名错误,这就是我需要的:

struct IFSFunc {
    int a;

    bool operator<(const IFSFunc& other) const {
        return a < other.a;
    }
};

请注意 operator< 现在是一个常量函数。

您需要将该运算符定义为常量成员函数。

此外,不要只是 return true 进行比较。这可能会导致无限循环。