I have a piece of code that confuses me:
sort(data, data+count, greater<int>() );
it is a sort function in the C standard library. I am having trouble figuring out the meaning of the third argument. I have read that it is called a binary predicate. What does that mean and how can I make my own such predicate?
The third argument is called a predicate. You can think of a predicate as a function that takes a number of arguments and returns
trueorfalse.So for example, here is a predicate that tells you whether an integer is odd:
The function above takes one argument, so you could call it a unary predicate. If it took two arguments instead, you would call it a binary predicate. Here is a binary predicate that tells you if its first argument is greater than the second:
Predicates are commonly used by very general-use functions to allow the caller of the function to specify how the function should behave by writing their own code (when used in this manner, a predicate is a specialized form of callback). For example, consider the
sortfunction when it has to sort a list of integers. What if we wanted it to sort all odd numbers before all even ones? We don’t want to be forced to write a new sort function each time that we want to change the sort order, because the mechanics (the algorithm) of the sort is clearly not related to the specifics (in what order we want it to sort).So let’s give
sorta predicate of our own to make it sort in reverse:Now this would sort in reverse order:
The way this works is that
sortinternally compares pairs of integers to decide which one should go before the other. For such a pairxandy, it does this by callingisLarger(x, y).So at this point you know what a predicate is, where you might use it, and how to create your own. But what does
greater<int>mean?greater<T>is a binary predicate that tells if its first argument is greater than the second. It is also a templatedstruct, which means it has many different forms based on the type of its arguments. This type needs to be specified, sogreater<int>is the template specialization for typeint(read more on C++ templates if you feel the need).So if
greater<T>is astruct, how can it also be a predicate? Didn’t we say that predicates are functions?Well,
greater<T>is a function in the sense that it is callable: it defines the operatorbool operator()(const T& x, const T& y) const;, which makes writing this legal:Objects of class type (or
structs, which is pretty much the same in C++) which are callable are called function objects or functors.