Hello again! In this video, we are going to look at library function objects. The C++ library defines
some function objects.
So these are generic operators which perform all the usual arithmetic, logical and relational operations.
So things like plus, greater than, not equals, and so on.
These are implemented as functors.
So these are classes which have a function call operator, and they are templated.
So these are completely generic.
They will work for any type which supports the underlying operator.
All these do,
is they just call the corresponding operator for the object.
For example, with the less-than operator, which is actually called less. This will have a function
call operator, which takes two arguments of the template type. And it returns a bool, which is the result
of calling the less than operator.
If we want to use this operator, we need to create an object.
So we need to call the constructor or do something else which will create an object.
We also need to give the paramater type. Although, in C++ 17, you can actually skip that.
So this will create an object of this functor, and then the sort() algorithm will call the function
call operator, which will in turn call the string's less-than operator.
So let's have a look at this. So we have a vector of strings.
We have our call to sort() with the function object as the arguments. Actually, let's remind ourselves
what happens without that.
So this is just the default ordering.
So these are ordered in ascending alphabetical order.
And that's because the sort() will use the string less-than operator by default.
So if we put this back, it is now going to use the library less, for type string, and that will also
use the less-than operator of the string class.
So we should expect to get exactly the same results and that is what we do.
There is something slightly more interesting if we use greater.
So this will now call the greater-than operator of the string class.
So we expect to get these sorted in the reverse order.
So with the highest first, in reverse alphabetical order.
OK.
And that is what we get.
So there is quite a few of these. They provide all the usual operations.
It is pretty obvious what the object does.
It may not always be obvious what the name of the object should be.
I am not sure I would have chosen the same ones - but there you go.
So those are for arithmetic.
Then we have the relational operators: equal to, not equal to, greater, less, greater equal, less equal.
And logical operators: logical and, logical or, logical not, and some bitwise operators as well. The
not operator did not get in until C++ 14. For some reason.
OK, so that's it for this video.
I will see you next time, but until then, keep coding!