The comparator
struct is an example of something usually called a 'functor' in C++. A functor is a 'callable object' - that is a regular object that implements operator()
, the function call operator. When used like this in an STL container, you are passing the type of the functor rather than an instance of it as a template argument. The container will create instances as necessary in order to actually call operator()
on them.
If you are familiar with lambdas in C++, they are really just syntactic sugar for functors. A lambda definition creates an anonymous type which you can think of as a compiler-generated functor type with an operator()
corresponding to the lambda function.
Functors (or lambdas) are the standard way in C++ to pass functions to types or other functions. This is useful in many situations, the example allows you to customize the sorting criteria for the priority_queue
. The STL uses functors all over the place in containers and the algorithms library as a way to parameterize types and functions on a user supplied function.