C++ <algorithm> - min() Function
The C++ algorithm::min function returns the smallest of a and b. The initializer list version of function returns the smallest element present in the list.
Syntax
//default version template <class T> const T& min (const T& a, const T& b); //custom version template <class T, class Compare> const T& min (const T& a, const T& b, Compare comp);
//default version template <class T> const T& min (const T& a, const T& b); //custom version template <class T, class Compare> const T& min (const T& a, const T& b, Compare comp); //initializer list version template <class T> T min (initializer_list<T> il); template <class T, class Compare> T min (initializer_list<T> il, Compare comp);
//default version template <class T> constexpr const T& min (const T& a, const T& b); //custom version template <class T, class Compare> constexpr const T& min (const T& a, const T& b, Compare comp); //initializer list version template <class T> constexpr T min (initializer_list<T> il); template <class T, class Compare> constexpr T min (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 the smallest of a and b or in initializer list version it returns the smallest element present in the list.
Time Complexity
Linear i.e, Θ(n).
Example:
In the example below, the algorithm::min function is used to find out the smallest of the values passed as arguments.
#include <iostream> #include <algorithm> using namespace std; int main (){ cout<<"min(100, 250): "<<min(100, 250)<<endl; cout<<"min(1.5, 1.9): "<<min(1.5, 1.9)<<endl; cout<<"min({1, 2, -5}): "<<min({1, 2, -5})<<endl; return 0; }
The output of the above code will be:
min(100, 250): 100 min(1.5, 1.9): 1.5 min({1, 2, -5}): -5
❮ C++ <algorithm> Library