struct point {
int x, y;
bool operator<(const point &p) {
if (x == p.x) return y < p.y;
else return x < p.x;
}
};
What does < between operator and (const point &p) signify?
struct point {
int x, y;
bool operator<(const point &p) {
if (x == p.x) return y < p.y;
else return x < p.x;
}
};
What does < between operator and (const point &p) signify?
What does
<
between operator and(const point &p)
signify?
It's a part of the member function name. It is a definition of a member function which is an overload of the <
operator. It is what makes this work:
point a{};
point b{};
if(a < b) { // point::operator<(const point&) is used here.
//
}
Note: The member function should really be const
qualified because calling the function does not change *this
(the lefthand side of <
).
bool operator<(const point &p) const {
// ^^^^^
... and it's also preferable if it's not even a member function, but a free function (taking two const point&
):
bool operator<(const point& lhs, const point &rhs) {
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
This is because if point
has an implicit conversion constructor, it will allow an instance of a type that is implicitly convertible to point
to appear on both the lefthand and righthand side of <
.
Example:
struct point {
point(int X, int Y) :x{X}, y{Y} {}
point(const std::pair<int, int>& pair) : x{pair.first}, y{pair.second} {}
int x, y;
};
bool operator<(const point& lhs, const point &rhs) {
return std::tie(lhs.x, lhs.y) < std::tie(rhs.x, rhs.y);
}
int main() {
std::pair<int, int> ip{10,20};
point pnt{10,19};
// This works with operator< as a member function or a free function:
if(pnt < ip) std::cout << "pnt < ip\n";
// This will not work if `operator<` is a member function:
if(ip < pnt) std::cout << "ip < pnt\n";
// ^^
// implicitly converted to `point`
}