C++ std::max_element

The std::max_element function in C++ is used to find the largest element in a range. It is useful for working with iterators to determine the maximum value in containers such as arrays, vectors, or lists.


Syntax of std::max_element

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

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

Parameters of std::max_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 maximum. Defaults to <.

Return Value of std::max_element

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


Examples for std::max_element

Example 1: Basic Usage of std::max_element

This example demonstrates finding the largest element in a vector.

Steps:

  1. Initialize a vector named nums with the elements {10, 20, 5, 40, 15}.
  2. Use the std::max_element function to find the largest element in the range defined by nums.begin() and nums.end().
  3. The function returns an iterator pointing to the largest element in the range.
  4. Check if the iterator is not equal to nums.end() to ensure the range is not empty.
  5. If the range is not empty, dereference the iterator using *it to access the largest element, and print it to the console.
  6. If the range is empty, print a message stating that no elements are available.

Program

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

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

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

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

    return 0;
}

Output:

Largest element: 40

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

This example demonstrates finding the largest element based on a custom comparison function.

Steps:

  1. Define a custom comparison function named abs_compare. This function compares two integers based on their absolute values using std::abs.
  2. Initialize a vector named nums with the elements {-10, 20, -5, 40, -15}.
  3. Use the std::max_element function with three arguments:
    • nums.begin(): The start of the range to search.
    • nums.end(): The end of the range to search.
    • abs_compare: The custom comparison function to determine the largest element by absolute value.
  4. The function returns an iterator pointing to the largest element based on the absolute value.
  5. Check if the iterator is not equal to nums.end() to ensure the range is not empty.
  6. If the range is not empty, dereference the iterator using *it to access the largest element by absolute value, and print it to the console.
  7. If the range is empty, print a message stating that no elements are available.

Program

</>
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::max_element(nums.begin(), nums.end(), abs_compare);

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

    return 0;
}

Output:

Largest element by absolute value: 40

Exception Handling in std::max_element

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

Steps:

  1. Define a custom comparison function named faulty_compare. This function compares two integers but throws a std::runtime_error if either integer is 40. Otherwise, it compares the integers in ascending order.
  2. Initialize a vector named nums with the elements {10, 20, 40, 5, 15}.
  3. Wrap the std::max_element function call in a try block to handle potential exceptions caused by the custom comparison function.
  4. Call std::max_element with three arguments:
    • nums.begin(): The start of the range to search.
    • nums.end(): The end of the range to search.
    • faulty_compare: The custom comparison function to determine the largest element.
  5. If faulty_compare encounters the value 40, it throws a std::runtime_error, interrupting the operation.
  6. In the catch block, capture the exception and print an error message to the console using std::cerr.
  7. If no exception is thrown, check if the iterator returned by std::max_element is not equal to nums.end() to ensure the range is not empty.
  8. If the range is not empty, dereference the iterator using *it to access the largest element, and print it to the console.
  9. If the range is empty, print a message stating that no elements are available.

Program

</>
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 it = std::max_element(nums.begin(), nums.end(), faulty_compare);

        if (it != nums.end()) {
            std::cout << "Largest 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 40 is not allowed.