C++ std::minmax

The std::minmax function in C++ returns the smaller and larger of two values, or the smallest and largest elements in an initializer list, as a pair. It is used when both minimum and maximum values are needed simultaneously.


Syntax of std::minmax

</>
Copy
template <class T>
std::pair<const T&, const T&> minmax(const T& a, const T& b);

template <class T, class Compare>
std::pair<const T&, const T&> minmax(const T& a, const T& b, Compare comp);

template <class T>
std::pair<T, T> minmax(std::initializer_list<T> ilist);

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

Parameters of std::minmax

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 <.
Parameters of std::minmax

Return Value of std::minmax

Returns a std::pair containing the smaller value as the first element and the larger value as the second element. For an initializer list, it returns a std::pair of the smallest and largest elements.


Examples for std::minmax

Example 1: Basic Usage of std::minmax

This example demonstrates finding the minimum and maximum of two integers:

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

int main() {
    int a = 10, b = 20;

    auto result = std::minmax(a, b);

    std::cout << "Minimum: " << result.first << ", Maximum: " << result.second << std::endl;

    return 0;
}

Output:

Minimum: 10, Maximum: 20

Explanation:

  1. We declared two integer variables, a and b, and initialized them with the values 10 and 20, respectively.
  2. The std::minmax function is used to find both the minimum and maximum of the two values. It returns a std::pair containing the smaller value as first and the larger value as second.
  3. The result of the std::minmax operation is stored in the variable result, which is of type std::pair<int, int>.
  4. The minimum and maximum values are accessed using result.first and result.second, respectively, and printed to the console using std::cout.
  5. The program terminates successfully after displaying the minimum and maximum values.

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

You can use a custom comparison function to define the criteria for finding the minimum and 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;

    auto result = std::minmax(a, b, abs_compare);

    std::cout << "Minimum by absolute value: " << result.first << ", Maximum by absolute value: " << result.second << std::endl;

    return 0;
}

Output:

Minimum by absolute value: 5, Maximum by absolute value: -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 declared two integer variables, a and b, initialized with the values -10 and 5, respectively.
  3. The std::minmax function is used with three arguments: a, b, and the custom comparison function abs_compare. It returns a std::pair containing the smaller value (by absolute magnitude) as first and the larger value (by absolute magnitude) as second.
  4. The result of the std::minmax operation is stored in the variable result, which is of type std::pair<int, int>.
  5. The minimum and maximum values (based on absolute magnitude) are accessed using result.first and result.second, respectively, and printed to the console using std::cout.

Exception Handling in std::minmax

The std::minmax function itself does not throw exceptions, but the comparison function passed as an argument may throw exceptions.

Example 1: Exception in Custom Comparison Function

This example demonstrates how exceptions in the custom comparison function are handled:

</>
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;

        auto result = std::minmax(a, b, faulty_compare);

        std::cout << "Minimum: " << result.first << ", Maximum: " << result.second << 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::minmax function, anticipating potential exceptions from the custom comparison function.
  4. The std::minmax function attempts to find both the minimum and maximum of a and b using the custom comparison function faulty_compare. When the value 5 is encountered, the function throws a std::runtime_error.
  5. The catch block captures the exception and prints an error message to the console using std::cerr, explaining what went wrong.
  6. The program terminates gracefully after handling the exception, ensuring no unhandled errors disrupt execution.