Figure 16.13 demonstrates algorithms min
, max
, minmax
and minmax_element
.
1 // Fig. 16.13: fig16_13.cpp
2 // Algorithms min, max, minmax and minmax_element.
3 #include <iostream>
4 #include <array>
5 #include <algorithm>
6 using namespace std;
7
8 int main()
9 {
10 cout << "The minimum of 12 and 7 is: " << min( 12, 7 );
11 cout << "
The maximum of 12 and 7 is: " << max( 12, 7 );
12 cout << "
The minimum of 'G' and 'Z' is: " << min( 'G', 'Z' );
13 cout << "
The maximum of 'G' and 'Z' is: " << max( 'G', 'Z' );
14
15 // determine which argument is the min and which is the max
16 auto result1 = minmax( 12, 7 );
17 cout << "
The minimum of 12 and 7 is: " << result1.first
18 << "
The maximum of 12 and 7 is: " << result1.second;
19
20 array< int, 10 > items = { 3, 100, 52, 77, 22, 31, 1, 98, 13, 40 };
21 ostream_iterator< int > output( cout, " " );
22
23 cout << "
Array items contains: ";
24 copy( items.cbegin(), items.cend(), output );
25
26 auto result2 = minmax_element( items.cbegin(), items.cend() );
27 cout << "
The minimum element in items is: " << *result2.first
28 << "
The maximum element in items is: " << *result2.second
29 << endl;
30 } // end main
The minimum of 12 and 7 is: 7
The maximum of 12 and 7 is: 12
The minimum of 'G' and 'Z' is: G
The maximum of 'G' and 'Z' is: Z
The minimum of 12 and 7 is: 7
The maximum of 12 and 7 is: 12
Array items contains: 3 100 52 77 22 31 1 98 13 40
The minimum element in items is: 1
The maximum element in items is: 100
Algorithms min and max (demonstrated in lines 10–13) determine the minimum and the maximum of two elements, respectively.
C++11 now includes overloaded versions of the algorithms min
and max
that each receive an initializer_list
parameter and return the smallest or largest item in the list initializer that’s passed as an argument. For example, the following statement returns 7
:
int minumum = min( { 10, 7, 14, 21, 17 } );
Each of these new min
and max
algorithms is overloaded with a version that takes as a second argument a binary predicate function for comparing values.
C++11 now includes the minmax algorithm (line 16) that receives two items and returns a pair
in which the smaller item is stored in first
and the larger item is stored in second
. A second version of this algorithm takes as a third argument a binary predicate function for comparing values.
C++11 now includes the minmax_element algorithm (line 26) that receives two input iterators representing a range of elements and returns a pair
of iterators in which first
points to the smallest element in the range and second
points to the largest. A second version of this algorithm takes as a third argument a binary predicate function for comparing values.