Reputation: 6352
I have a struct defined like this:
struct IFSFunc {
int a;
bool operator<(const IFSFunc& other) {
return a < other.a;
}
};
Since IFSfunc
is a struct
, access modifier for the operator<
should be public
.
I also have this code:
#include <algorithm>
std::vector<std::pair<double, IFSFunc>> ifsFuncs;
// fill the vector with various data
std::sort(ifsFuncs.begin(), ifsFuncs.end());
I need to sort ifsFuncs based on the first double
in the pair. I don't care about IFSFunc
structure, if the double
is the same.
However, for std::sort to work, which is defined like this:
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);
}
I have to override the less than operator for the second
in this case IFSfunc
, which I did. However, trying to compile this code gives me the following error:
Error C2678 binary '<': no operator found which takes a left-hand operand of type 'const _Ty2' (or there is no acceptable conversion)
Why?
Upvotes: 0
Views: 904
Reputation: 54325
You need to define that operator as a const member function.
Also, don't just return true for a comparison. That can result in infinite looping.
Upvotes: 3
Reputation: 6352
I just figure it out. The overloaded function signature was wrong, this is what I need:
struct IFSFunc {
int a;
bool operator<(const IFSFunc& other) const {
return a < other.a;
}
};
Notice that the operator<
is now a const function.
Upvotes: 0