I’m confused that when do we use normal bool comparator like bool comp(int a, int b) return a>b;
and when do we use the functional object used in class, like
class comp
{
bool operator()(int a, int b){
return a>b;
}
}
When do we use the bool comparator and when do we use the functional object?
Comparators are used in sort( ) to define any kind of sorting other than the standard ascending order sorting. You can create and use your own custom comparators to sort a variety of data in any fashion you wish , like the one you wrote above.
Functional Objects ( or simply Functors ) are class objects which look and act like functions are much widely used and offer a variety of functionality. A lot of STL classes which do some kind of ordering ( like priority queues , map etc.) can be defined to do the ordering/sorting based on some custom criteria using Functors.
There are several predefined functors available to you in the header file “functional” .
Eg- greater < >
You can also define your own functors like you did in the question and use them to define a different ordering.
As for when to use which , comparators are only used in sort( ) and other such sorting functions like qsort( ). That is , basically when you are passing a comparison to a function , you use a comparator.
Whereas when you are passing the comparison criteria to a STL class like priority_queue , you use a functor (predefined or custom) .