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