std::max in C++
The std::max() is the built-in function in C++ used for finding the maximum among two or more elements passed to it as arguments. It is defined inside <algorithm> header file. In this article, we will learn how to use std::max() function in C++.
The std::max() can be used in the following ways:
Find Maximum Among Two Values
We can use std::max() function to find the larger among two values. We can also compare the two values using different parameters by defining the custom comparison function.
Syntax
max(a , b, comp);
Parameters
- a: First value to be compared.
- b: Second value to be compared.
- comp: Binary function that accepts two values and returns a value convertible to bool. It is optional and by default set to return true if the first element is larger than second.
Return Value
- Returns the larger of the two values.
- If both are equal, returns the first value.
The std::max
function is essential for finding the maximum value between two values.
Example: Finding Maximum Among Two Numbers using std::max()
// C++ program to find the larger number among
// two numbers using std::max()
#include <bits/stdc++.h>
using namespace std;
// Custom compare function
bool comp(int a, int b) {
return a > b;
}
int main() {
int a = 8, b = 91;
// Finding maximum among two numbers
cout << max(a, b) << endl;
// Again doing the same but with custom comparator
cout << max(a, b, comp) << endl;
return 0;
}
Output
91 8
Time Complexity: O(1)
Auxiliary Space: O(1)
Find the Maximum Among the Multiple Values
The std::max() function can also find the maximum value between more than two values. We have to pass the values enclosed in { } braces and separated by a comma (initializer list).
Syntax
max ({v1, v2, v3...}, comp);
Parameters:
- v1, v2, v3...: List of values.
- comp: Optional comparator function to change the way of comparison.
Return Value
- Returns the largest value among the given lists.
- If all are equal, return the first value.
Example: Finding Largest Value Among the List of Integers
// C++ program to demonstrate how to find the
// largest number among the list of numbers
// using std::max()
#include<bits/stdc++.h>
using namespace std;
int main() {
// Finding the largest of all the numbers
cout << max({1, 2, 3, 4, 5, 10, -1, 7})
<< endl;
return 0;
}
Output
10
Time Complexity: O(n), where n is the number of elements.
Auxiliary Space: O(1)