Last Updated : 11 Jan, 2025
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 ValuesWe 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.
Syntaxmax(a , b, comp);
Parameters
Return Value
The std::max
function is essential for finding the maximum value between two values.
// 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;
}
Time Complexity: O(1)
Auxiliary Space: O(1)
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).
Syntaxmax ({v1, v2, v3...}, comp);
Parameters:
Return Value
// 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;
}
Time Complexity: O(n), where n is the number of elements.
Auxiliary Space: O(1)
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4