C++ std::minmax_element

The std::minmax_element function in C++ is used to find both the smallest and largest elements in a range. It returns a pair of iterators, where the first points to the smallest element and the second points to the largest. This function is particularly useful for finding both extremes in a single pass.


Syntax of std::minmax_element

</>
Copy
template <class ForwardIterator>
std::pair<ForwardIterator, ForwardIterator> 
minmax_element(ForwardIterator first, ForwardIterator last);

template <class ForwardIterator, class Compare>
std::pair<ForwardIterator, ForwardIterator> 
minmax_element(ForwardIterator first, ForwardIterator last, Compare comp);

Parameters of std::minmax_element

ParameterDescription
first, lastForward iterators defining the range to search. The range is [first, last).
comp (optional)A binary comparison function that defines the criteria for finding the smallest and largest elements. Defaults to <.

Return Value of std::minmax_element

Returns a std::pair of iterators:

  • first: Iterator pointing to the smallest element in the range.
  • second: Iterator pointing to the largest element in the range.

If the range is empty, both iterators in the pair are equal to last.


Examples for std::minmax_element

Example 1: Basic Usage of std::minmax_element

This example demonstrates finding the smallest and largest elements in a vector:

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

int main() {
    std::vector<int> nums = {10, 20, 5, 40, 15};

    auto result = std::minmax_element(nums.begin(), nums.end());

    if (result.first != nums.end() && result.second != nums.end()) {
        std::cout << "Smallest element: " << *result.first << std::endl;
        std::cout << "Largest element: " << *result.second << std::endl;
    } else {
        std::cout << "The range is empty." << std::endl;
    }

    return 0;
}

Explanation:

  1. Include necessary headers:
    • <iostream> is included for input/output operations.
    • <algorithm> is included for the std::minmax_element function.
    • <vector> is included for the std::vector container.
  2. Initialize a vector:
    • A vector named nums is created and initialized with the elements {10, 20, 5, 40, 15}.
  3. Find the smallest and largest elements:
    • The function std::minmax_element is called with the range nums.begin() and nums.end().
    • This function returns a pair of iterators:
      • result.first: Iterator pointing to the smallest element in the range.
      • result.second: Iterator pointing to the largest element in the range.
  4. Check if the range is valid:
    • The program checks if both result.first and result.second are not equal to nums.end(), indicating that the range is not empty.
  5. Display the results:
    • If the range is valid:
      • The smallest element is accessed using *result.first and displayed.
      • The largest element is accessed using *result.second and displayed.
    • If the range is empty, the program outputs "The range is empty.".

Output:

Smallest element: 5
Largest element: 40

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

This example demonstrates finding the smallest and largest elements based on a custom comparison function:

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

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

int main() {
    std::vector<int> nums = {-10, 20, -5, 40, -15};

    auto result = std::minmax_element(nums.begin(), nums.end(), abs_compare);

    if (result.first != nums.end() && result.second != nums.end()) {
        std::cout << "Smallest element by absolute value: " << *result.first << std::endl;
        std::cout << "Largest element by absolute value: " << *result.second << std::endl;
    } else {
        std::cout << "The range is empty." << std::endl;
    }

    return 0;
}

Explanation:

  1. Define a custom comparison function:
    • The function abs_compare takes two integers, a and b, as input.
    • It compares the absolute values of the two integers using std::abs.
    • It returns true if the absolute value of a is less than that of b, and false otherwise.
  2. Initialize a vector:
    • A vector named nums is created and initialized with the elements {-10, 20, -5, 40, -15}.
  3. Find the smallest and largest elements by absolute value:
    • The function std::minmax_element is called with the range nums.begin() and nums.end(), and the custom comparison function abs_compare is passed as the third argument.
    • This function returns a pair of iterators:
      • result.first: Iterator pointing to the element with the smallest absolute value in the range.
      • result.second: Iterator pointing to the element with the largest absolute value in the range.
  4. Check if the range is valid:
    • The program checks if both result.first and result.second are not equal to nums.end(), indicating that the range is not empty.

Output:

Smallest element by absolute value: -5
Largest element by absolute value: 40

Exception Handling in std::minmax_element

The std::minmax_element function does not throw exceptions on its own. However, the comparison function passed as an argument may throw exceptions, which can be caught and handled appropriately.

Example 1: Exception in Custom Comparison Function

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

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

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

int main() {
    std::vector<int> nums = {10, 20, 40, 5, 15};

    try {
        auto result = std::minmax_element(nums.begin(), nums.end(), faulty_compare);

        if (result.first != nums.end() && result.second != nums.end()) {
            std::cout << "Smallest element: " << *result.first << std::endl;
            std::cout << "Largest element: " << *result.second << std::endl;
        } else {
            std::cout << "The range is empty." << std::endl;
        }
    } catch (const std::exception& e) {
        std::cerr << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Explanation:

  1. Define a custom comparison function:
    • faulty_compare is a custom function that compares two integers, a and b.
    • The function throws a std::runtime_error exception if either a or b equals 40, with the message "Comparison involving 40 is not allowed.".
    • If no exception is thrown, the function compares a and b and returns true if a is less than b, and false otherwise.
  2. Attempt to find the smallest and largest elements:
    • The function std::minmax_element is called with the range nums.begin() and nums.end(), along with the custom comparison function faulty_compare.
    • If the function completes without exceptions, it returns a pair of iterators:
      • result.first: Iterator pointing to the smallest element.
      • result.second: Iterator pointing to the largest element.
  3. Handle exceptions:
    Use try-catch block.
    • If faulty_compare throws a std::runtime_error, the catch block captures the exception.
    • The exception message is displayed using std::cerr.
  4. Display the results:
    • If no exception occurs and the range is valid (i.e., result.first != nums.end() and result.second != nums.end()):
      • The smallest element is accessed using *result.first and displayed.
      • The largest element is accessed using *result.second and displayed.
    • If the range is empty, the program outputs "The range is empty.".

Output:

Exception caught: Comparison involving 40 is not allowed.