Home »
C++ STL
std::max() function with example in C++ STL
C++ STL | std::max() function: Here, we are going to learn about the max() function of algorithm header in C++ STL with example.
Submitted by IncludeHelp, on May 20, 2019
C++ STL std::max() function
max() function is a library function of algorithm header, it is used to find the largest value from given two values, it accepts two values and returns the largest value and if both the values are the same it returns the first value.
Note:To use max() function – include <algorithm> header or you can simple use <bits/stdc++.h> header file.
Syntax of std::max() function
std::max(const T& a, const T& b);
std::max() Parameter(s)
const T& a, const T& b – values to be compared.
std::max() Return value
T – it returns the largest value of type T.
Example:
Input:
int a = 10;
int b = 20;
//finding largest value
cout << max(a,b) << endl;
Output:
20
C++ STL program to demonstrate use of std::max() function
In this example, we are going to find the largest values from given values of different types.
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
cout << "max(10,20) : " << max(10, 20) << endl;
cout << "max(10.23f,20.12f): " << max(10.23f, 20.12f) << endl;
cout << "max(-10,-20) : " << max(-10, -20) << endl;
cout << "max('A','a') : " << max('A', 'a') << endl;
cout << "max('A','Z') : " << max('A', 'Z') << endl;
cout << "max(10,10) : " << max(10, 10) << endl;
return 0;
}
Output
max(10,20) : 20
max(10.23f,20.12f): 20.12
max(-10,-20) : -10
max('A','a') : a
max('A','Z') : Z
max(10,10) : 10
Reference: C++ std::max()