I am trying to learn C++ STL..I came across this syntax,not able to figure out what the whole line means!
struct student{
int id,pts;
bool operator < (student x) const{
return pts>x.pts;
}
}a[150000];
I am trying to learn C++ STL..I came across this syntax,not able to figure out what the whole line means!
struct student{
int id,pts;
bool operator < (student x) const{
return pts>x.pts;
}
}a[150000];
it is defining a "less than" operator for the struct student
, so that people can write:
student one, two;
bool b = one < two;
operator< allows comparing two students, and in this example, it compares only by pts.
struct student{
int id,pts;
bool operator < (student x) const{
return pts>x.pts; // must be pts<x.pts
}
}a[150000];
lest should it work the other way (operator >), the implementation must use operator '<'
As a good practice, please consider adding custom definition for operator > and operator=, because the comparison is based only on pts (by the definition of operator <)
For the sake of minimal completeness and logical correctness when using comparison operators, please consider adding custom definition for operators > and ==
struct student{
int id,pts;
bool operator < (student x) const{
return pts<x.pts;
}
bool operator > (student x) const{
return pts>x.pts;
}
bool operator == (student x) const{
return pts == x.pts;
}
}a[150000];
operator <
is a name to be defined, just like foo
or bar
. It behaves just like an identifier.
bool operator < (student x) const
declares a function as bool foo (student x) const
would.
The effect is to define usage of the <
operator between student
objects. The connection to the STL is that templates related to ordering of objects use expressions like a < b
to perform the ordering. This comes up in algorithms like std::sort
and containers like std::map
.
That particular definition sorts students by points, which isn't a very good system for sorting students. Facilities like sort
and map
always provide an alternative to operator <
, where you can pass a more specific function, say one called less_points
. Also, since that definition of operator <
uses the >
operator internally (without reversing the left- and right-hand sides), it will sort in descending order whereas the usual convention is to use ascending order.
Note, it's common to define operator <
or operator ==
without defining >
, !=
, or the other relational operators. The standard library only ever cares about <
and ==
, and boilerplate to get the rest is usually wasted. Likewise it's a good convention to avoid using relations besides <
and ==
on objects that might not be numbers.