我有一个结构是这样定义的。
struct IFSFunc {
int a;
bool operator<(const IFSFunc& other) {
return a < other.a;
}
};
自... IFSfunc
是一个 struct
的访问修改器。operator<
应是 public
.
我也有这样的代码。
#include <algorithm>
std::vector<std::pair<double, IFSFunc>> ifsFuncs;
// fill the vector with various data
std::sort(ifsFuncs.begin(), ifsFuncs.end());
我需要根据第一个ifsFuncs进行排序。double
在对。我不关心 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);
}
我必须覆盖小于运算符来处理 second
在此 IFSfunc
我做了。然而,试图编译这段代码时,我得到了以下错误。
Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const _Ty2' (or there is no acceptable conversion)
为什么?
你需要将该操作符定义为一个const成员函数。
另外,不要只对比较返回true。那样会导致无限循环。
我只是想明白了。重载函数的签名是错误的,这是我需要的。
struct IFSFunc {
int a;
bool operator<(const IFSFunc& other) const {
return a < other.a;
}
};
注意 operator<
现在是一个构造函数。