Hello again! In this video, we are going to look at min and max algorithms.
The standard library provides quite a few algorithms for finding the largest or smallest elements,
or sometimes both.
There are various functions which can take two arguments, an initializer list in C++11, or the
traditional iterator range.
By default, these will use the less-than operator of the element, or the argument, to find out the
largest or smallest.
But we can provide our own comparison operator, as a predicate.
And I think, probably, rather than having lots of very similar slides, the best way to demonstrate this
is to have a program.
So here it is. We start off with a couple of string variables.
The less-than operator will do alphabetical comparisons.
So "first_word" will be less than "word2". The basic functions
are just max and min with two arguments.
And these will return the largest or the smallest element.
We can also provide a predicate, for example, if we want to use the size of the string and not the
alphabetical order of the characters. We can pass an initialize the list, and this will return
the largest or the smallest element in the list.
So we would expect to get "words" for the max(), and "collection" for the min().
There is minmax(), which will return a pair of values. So this will find both the minimum and the maximum.
You can either give it 2 arguments or an initializer list.
The first member of the returned pair will be the smallest argument or element, and the second member
will be the largest.
min_element() and max_element() will take an iterator range.
We are going to use this vector as a container, to provide the iterator range. Then we pass the iterator
range to max_element().
And this will return an [iterator] to the largest element in here.
So that will be the "words".
And again, we can provide a predicate if we want to.
So this will return an iterator to the shortest element in the iterator range, which will
be the letter 'a'.
And then finally, we have minimax_element(), which combines minmax() and these two functions.
So this will take an iterator range, like these two do.
And it will return a pair of iterators, like minmax() does.
And then the first member of the pair will be an iterator to the smallest element, and the second member
will be an iterator to the largest element.
So let's see what we get.
So "word2" is greater than "first_word", "first_word" has more characters than "word2", and we get the
expected values from those.
Okay, so you may not find all of these useful, but they are there. Probably the most useful is just the version
which takes two arguments and then the initializer list as well, perhaps.
Okay, so that is it for this video.
I will see you next time.
Until then, keep coding!