C++ std::min_element

The algorithm std::min_element function in C++ is used to find the smallest element in a range. It is used when working with iterators to find the minimum value in containers like arrays, vectors, or lists.


Syntax of std::min_element

</>
Copy
template <class ForwardIterator>
ForwardIterator min_element(ForwardIterator first, ForwardIterator last);

template <class ForwardIterator, class Compare>
ForwardIterator min_element(ForwardIterator first, ForwardIterator last, Compare comp);

Parameters of std::min_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 the minimum. Defaults to <.
Parameters of std::min_element

Return Value of std::min_element

Returns an iterator pointing to the smallest element in the range. If the range is empty, last is returned.


Examples for std::min_element

Example 1: Basic Usage of std::min_element

In this example, we will show how to find the smallest element in a vector:

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

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

    auto it = std::min_element(nums.begin(), nums.end());

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

    return 0;
}

Output:

Smallest element: 5

Explanation:

  1. We initialized a vector named nums with the elements {10, 20, 5, 40, 15}.
  2. The std::min_element function is used to find the smallest element in the range [nums.begin(), nums.end()). It returns an iterator pointing to the smallest element.
  3. A conditional check is performed to verify if the iterator returned by std::min_element is not equal to nums.end(). If true, it means the range is not empty, and the smallest element can be accessed using *it.
  4. The smallest element is printed to the console using std::cout.
  5. If the range is empty (which is not the case here), a message is printed to indicate that no elements are available.

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

This example demonstrates finding the smallest element 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 it = std::min_element(nums.begin(), nums.end(), abs_compare);

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

    return 0;
}

Output:

Smallest element by absolute value: -5

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 initialized a vector named nums with the elements {-10, 20, -5, 40, -15}, which include both positive and negative values.
  3. The std::min_element function is used with three arguments: nums.begin(), nums.end(), and the custom comparison function abs_compare. It finds the smallest element in the range based on its absolute value.
  4. A conditional check is performed to ensure that the iterator returned by std::min_element is not equal to nums.end(). If true, it means the range is not empty, and the smallest element (by absolute value) can be accessed using *it.
  5. The smallest element, based on absolute value, is printed to the console using std::cout.

Exception Handling in std::min_element

The std::min_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.

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 == 5 || b == 5) {
        throw std::runtime_error("Comparison involving 5 is not allowed.");
    }
    return a < b;
}

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

    try {
        auto it = std::min_element(nums.begin(), nums.end(), faulty_compare);

        if (it != nums.end()) {
            std::cout << "Smallest element: " << *it << 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;
}

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 initialized a vector named nums with the elements {10, 20, 5, 40, 15}.
  3. A try block is used to safely execute the std::min_element function, anticipating potential exceptions from the custom comparison function.
  4. The std::min_element function is called with three arguments: nums.begin(), nums.end(), and the custom comparison function faulty_compare. It attempts to find the smallest element in the range based on the comparison logic.
  5. During execution, when faulty_compare encounters the value 5, it throws a std::runtime_error, halting further comparisons.
  6. The catch block captures the exception and prints an error message to the console using std::cerr, explaining the cause of the exception.
  7. If no exception were thrown, the program would check if the iterator returned by std::min_element is not equal to nums.end(). If true, it would print the smallest element. If the range were empty, it would display a message indicating this.