Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the "operator <" syntax mean?

Tags:

syntax

c++11

stl

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];

2 Answers

it is defining a "less than" operator for the struct student, so that people can write:

 student one, two;
 bool b = one < two;
like image 182
Marshall Clow Avatar answered Feb 15 '26 12:02

Marshall Clow


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.

like image 32
Potatoswatter Avatar answered Feb 15 '26 13:02

Potatoswatter