std::max in C++

Last Updated : 5 Jun, 2026

The std::max() function is a built-in function in C++ that returns the largest value among two or more values. It is defined in the <algorithm> header file and is commonly used to simplify comparison operations in programs.

C++
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
    int a = 25, b = 40;

    cout << "Maximum Value: " << max(a, b);

    return 0;
}

Output
Maximum Value: 40

Explanation: std::max() compares 25 and 40 and returns the larger value, which is 40.

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.

C++
#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.
C++
#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)

Comment