C++ std::max function is a built-in function defined inside <algorithm> header file and is used to find out the largest number passed to it. It returns the first of them if there is more than one.
It can be implemented in the following manners:
- It compares the two numbers passed in its arguments and returns the larger of the two, and if both are equal, then it returns the first one.
- It can also compare the two numbers using a binary function, which is defined by the user, and then passed as an argument in std::max().
- It is also helpful if we want to find the largest element in a given list, and it returns the first one if there is more than one present in the list.
1. For comparing elements as using “<“:
Syntax:
const T& max (const T& a, const T& b);
Parameters:
- a: value to be compared
- b: value to be compared
Return Value:
- Returns the larger of the two values.
- If both are equal, returns the first value.
Note: T is the typename defined in the class template.
Example:
C++
#include <algorithm>
#include <iostream>
using namespace std;
int main()
{
cout << std::max( 'a' , 'b' ) << "\n" ;
cout << std::max(7, 7);
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
2. For comparing elements using a pre-defined function:
Syntax:
const T& max (const T& a, const T& b, Compare comp);
Parameters:
- a: value to be compared
- b: value to be compared
- comp: Binary function that accepts two values of type T as arguments, and returns a value convertible to bool. The value returned indicates whether the element passed as the first argument is considered less than the second.
Return Value:
- Returns the larger of the two values.
- If both are equal, return the first value.
Example:
C++
#include<iostream>
#include<algorithm>
using namespace std;
bool comp( int a, int b)
{
return (a < b);
}
int main()
{
int a = 7;
int b = 28;
cout << std::max(a,b,comp) << "\n" ;
cout << std::max(7,7,comp);
return 0;
}
|
Time Complexity: O(1)
Auxiliary Space: O(1)
3. For finding the maximum element in a list:
Syntax:
T max (initializer_list il, Compare comp);
Parameters:
- il: An initializer_list object.
- comp: comparator function which is optional and can be skipped.
Return Value: The largest value of the list is returned.
Below is the C++ program for finding the maximum element in a list:
CPP
#include<iostream>
#include<algorithm>
using namespace std;
bool comp( int a, int b)
{
return (a < b);
}
int main()
{
cout << std::max({1, 2, 3, 4, 5, 10, -1, 7},comp) << "\n" ;
return 0;
}
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Articles:
Last Updated :
06 Jan, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...