What is the minmax() function in C++?

The minmax() function in C++ accepts two values or an array of elements and returns the minimum and maximum element as a pair. This function is available in <algorithm.h>.

Parameters

There can be two versions of the minmax() function. The first version accepts the following parameters:

  • first_value, second_value: These are the values compared against each other.

You need to pass the two values of same type.

  • comparator: This is an optional parameter that specifies the condition when the first value should come and when the second value should come. In other words, you can pass a function that returns a Boolean value that denotes which value to is lesser out of the two given values.

The second version of the minmax() function accepts the following parameters:

  • arr: This is an array of elements from which we want to find the minimum and maximum element.

  • comparator: This is an optional parameter that specifies the condition when the first value should come and when the second value should come. In other words, you can pass a function that returns a boolean value that denotes which value to is lesser out of the two given values.

Return

The minmax() function returns a pair containing two values. The first value will be the minimum element and the second value will be the maximum element.

Code

Let us have a look at the code now:

#include <iostream>
#include <algorithm>
using namespace std;
bool comp(int a, int b){
return a > b;
}
int main () {
// first version
pair<int, int> r1 = minmax(3, 8, comp);
cout << r1.first << " " << r1.second << endl;
// second version
pair<int, int> r2 = minmax({1,2,3,4,5});
cout << r2.first << " " << r2.second << endl;
return 0;
}

Explanation

  • In lines 1 and 2, we import the required header files.

  • From lines 5 to 7, we define a boolean function that accepts two parameters and returns true if the first parameter is greater than the second one. We will use this function as a parameter to the minmax() function.

  • In line 11, we call the first version of the minmax() function by passing the two values and the comparator function. Here, if you observe the output, then the first element will be the maximum, and the second element will be the minimum. This happened due to the comparator function. In the comparator function, we have reversed the logic to consider the minimum element.

  • In line 12, we print the result.

  • In line 15, we call the second version of the minmax() function, and we only pass the array of elements here. If you observe the output, then you can see that the first element in the result is the minimum and the second element in the result is the maximum. This is the default behavior as we have not passed the comparator function.

  • Finally, in line 16, we print the result.

So, in this way, we can use the minmax() function in C++ to easily get the minimum and maximum values from an array.

Free Resources