C++ <algorithm> - minmax() Function
The C++ algorithm::minmax function returns a pair containing the smallest and largest of a and b. The initializer list version of function returns a pair containing the smallest and largest elements present in the list. The pair contains first element as smallest number and second element as largest number.
Syntax
//default version template <class T> pair <const T&,const T&> minmax (const T& a, const T& b); //custom version template <class T, class Compare> pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp); //initializer list version template <class T> pair<T,T> minmax (initializer_list<T> il); template <class T, class Compare> pair<T,T> minmax (initializer_list<T> il, Compare comp);
//default version template <class T> constexpr pair <const T&,const T&> minmax (const T& a, const T& b); //custom version template <class T, class Compare> constexpr pair <const T&,const T&> minmax (const T& a, const T& b, Compare comp); //initializer list version template <class T> constexpr pair<T,T> minmax (initializer_list<T> il); template <class T, class Compare> constexpr pair<T,T> minmax (initializer_list<T> il, Compare comp);
Parameters
a |
Specify the first value to compare. |
b |
Specify the second value to compare. |
comp |
A binary predicate that takes two elements in the range as arguments and returns a bool. It follows the strict weak ordering to order the elements. |
il |
Specify the initializer list with the values to compare. |
Return Value
Returns a pair containing the smallest and largest of a and b. The initializer list version of function returns a pair containing the smallest and largest elements present in the list.
Time Complexity
Linear i.e, Θ(n).
Example:
In the example below, the algorithm::minmax function is used to find out the smallest and largest of the values passed as arguments.
#include <iostream> #include <algorithm> using namespace std; int main (){ auto retval1 = minmax(100, 200); auto retval2 = minmax({10, 3, -5, 27}); cout<<"minmax(100, 200): "; cout<<retval1.first<<" "<<retval1.second<<endl; cout<<"minmax({10, 3, -5, 27}): "; cout<<retval2.first<<" "<<retval2.second; return 0; }
The output of the above code will be:
minmax(100, 200): 100 200 minmax({10, 3, -5, 27}): -5 27
❮ C++ <algorithm> Library