C++ std::max

The std::max function in C++ returns the larger of two values or, in the case of an initializer list, the largest element in the list. It is part of the Standard Library and is commonly used in comparisons to determine the maximum value.


Syntax of std::max

</>
Copy
template <class T>
const T& max(const T& a, const T& b);

template <class T, class Compare>
const T& max(const T& a, const T& b, Compare comp);

template <class T>
T max(std::initializer_list<T> ilist);

template <class T, class Compare>
T max(std::initializer_list<T> ilist, Compare comp);

Parameters of std::max

ParameterDescription
a, bThe two values to compare.
ilistAn initializer list containing values to compare.
comp (optional)A binary comparison function that defines the comparison criteria. Defaults to < (less than).
Parameters of std::max

Return Value of std::max

Returns the larger of the two arguments, or the largest element in the initializer list, based on the comparison criteria.


Examples for std::max

Example 1: Basic Usage of std::max

This example demonstrates finding the maximum of two integers:

</>
Copy
#include <iostream>
#include <algorithm>

int main() {
    int a = 10, b = 20;
    std::cout << "Maximum of " << a << " and " << b << " is: " << std::max(a, b) << std::endl;
    return 0;
}

Output:

Maximum of 10 and 20 is: 20

Explanation:

  1. We declared two integer variables, a and b, and initialized them with the values 10 and 20, respectively.
  2. The std::max function is used to find the larger of the two values. It compares a and b and returns the greater value.
  3. The result of the comparison is printed to the console using std::cout, along with an explanatory message.
  4. The program terminates successfully after displaying the result.

Example 2: Using a Custom Comparison Function for std::max

You can use a custom comparison function to define the criteria for finding the maximum:

</>
Copy
#include <iostream>
#include <algorithm>

bool abs_compare(int a, int b) {
    return std::abs(a) < std::abs(b);
}

int main() {
    int a = -10, b = 5;
    std::cout << "Maximum by absolute value of " << a << " and " << b << " is: " << std::max(a, b, abs_compare) << std::endl;
    return 0;
}

Output:

Maximum by absolute value of -10 and 5 is: -10

Explanation:

  1. We defined a custom comparison function named abs_compare. This function compares the absolute values of two integers using std::abs.
  2. We then declared two integer variables, a and b, initialized with the values -10 and 5, respectively.
  3. The std::max function is used with three arguments: a, b, and the custom comparison function abs_compare. It returns the value with the larger absolute magnitude based on the custom comparison logic.

Exception Handling in std::max

The std::max function does not throw exceptions on its own, but the comparison function passed as an argument may throw exceptions.

Example 1: Exception in Custom Comparison Function

In this example, the custom comparison function throws an exception for specific values:

</>
Copy
#include <iostream>
#include <algorithm>
#include <stdexcept>

bool faulty_compare(int a, int b) {
    if (a == 5 || b == 5) {
        throw std::runtime_error("Comparison involving 5 is not allowed.");
    }
    return a < b;
}

int main() {
    try {
        int a = 5, b = 10;
        std::cout << "Maximum is: " << std::max(a, b, faulty_compare) << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }
    return 0;
}

Output:

Exception caught: Comparison involving 5 is not allowed.

Explanation:

  1. We defined a custom comparison function named faulty_compare. This function throws a std::runtime_error exception if either of the integers being compared is 5. Otherwise, it compares the integers in ascending order.
  2. We declared two integer variables, a and b, initialized with the values 5 and 10, respectively.
  3. A try block is used to safely execute the std::max function with a, b, and the custom comparison function faulty_compare.
  4. The std::max function attempts to compare the two integers using faulty_compare. When the value 5 is encountered, the custom comparison function throws a std::runtime_error.
  5. The catch block captures the exception and prints an error message to the console using std::cerr, describing what caused the exception.
  6. The program terminates gracefully after handling the exception, ensuring no unhandled errors disrupt execution.