The minmax_element()
function in C++ finds the minimum and maximum element’s positions in the specified range. This function is available in <algorithm.h>
.
The minmax_element()
function accepts the following parameters:
first
: This is an iterator pointing to the initial position of the range in which the minimum and maximum values need to be searched.
last
: This is an iterator pointing to the final range position till which minimum and maximum values need to be searched.
comparator
: This is an optional parameter that specifies the condition of when the first and second values should come. In other words, you can pass a function that returns a Boolean value that denotes which out of the two given values is lesser.
The minmax_element()
function returns a pair containing two values. The first value will be the iterator pointing to the minimum element, and the second value will be the iterator pointing to the maximum element.
#include <iostream>#include <algorithm>#include <vector>using namespace std;bool comp(int a, int b){return a > b;}int main () {vector<int> vec = {1, 2, 3, 4, 5, 6, 7, 8, 9};auto r1 = minmax_element(vec.begin(), vec.end(), comp);cout << "Output with Comparator Function: ";cout << *r1.first << " " << *r1.second << endl;cout << "Position of Min element: " << r1.first - vec.begin() << endl;cout << "Position of Max element: " << r1.second - vec.begin();cout << endl;auto r2 = minmax_element(vec.begin(), vec.end());cout << "Output without Comparator Function: ";cout << *r2.first << " " << *r2.second << endl;cout << "Position of Min element: " << r2.first - vec.begin() << endl;cout << "Position of Max element: " << r2.second - vec.begin();return 0;}
From lines 1 to 3, we imported the required header files.
From lines 6 to 8, we defined a boolean function that accepts two parameters and returns true
if the first parameter is greater than the second one.
We will pass this function as a parameter to the minmax_element()
function.
In line 12, we create a vector containing some integer elements.
In line 13, we call the minmax_element()
function by passing the two iterators and the comparator function. The first element is the maximum, and the second element is the minimum. This happened due to the comparator function. We have reversed the logic to consider the minimum element in the comparator function.
From lines 14 to 17, we print the result.
In line 20, we again call the minmax_element()
function and here we only pass the two iterators. If you observe the output, 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, from lines 21 to 24, we print the result.
So, in this way, we can easily use the minmax_element()
function in C++ to get the minimum and maximum values with their positions within a vector.