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
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
Parameter | Description |
---|---|
first, last | Forward 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:
#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:
- Include necessary headers:
<iostream>
is included for input/output operations.<algorithm>
is included for thestd::minmax_element
function.<vector>
is included for thestd::vector
container.
- Initialize a vector:
- A vector named
nums
is created and initialized with the elements{10, 20, 5, 40, 15}
.
- A vector named
- Find the smallest and largest elements:
- The function
std::minmax_element
is called with the rangenums.begin()
andnums.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.
- The function
- Check if the range is valid:
- The program checks if both
result.first
andresult.second
are not equal tonums.end()
, indicating that the range is not empty.
- The program checks if both
- 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.
- The smallest element is accessed using
- If the range is empty, the program outputs
"The range is empty."
.
- If the range is valid:
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:
#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:
- Define a custom comparison function:
- The function
abs_compare
takes two integers,a
andb
, as input. - It compares the absolute values of the two integers using
std::abs
. - It returns
true
if the absolute value ofa
is less than that ofb
, andfalse
otherwise.
- The function
- Initialize a vector:
- A vector named
nums
is created and initialized with the elements{-10, 20, -5, 40, -15}
.
- A vector named
- Find the smallest and largest elements by absolute value:
- The function
std::minmax_element
is called with the rangenums.begin()
andnums.end()
, and the custom comparison functionabs_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.
- The function
- Check if the range is valid:
- The program checks if both
result.first
andresult.second
are not equal tonums.end()
, indicating that the range is not empty.
- The program checks if both
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:
#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:
- Define a custom comparison function:
faulty_compare
is a custom function that compares two integers,a
andb
.- The function throws a
std::runtime_error
exception if eithera
orb
equals40
, with the message"Comparison involving 40 is not allowed."
. - If no exception is thrown, the function compares
a
andb
and returnstrue
ifa
is less thanb
, andfalse
otherwise.
- Attempt to find the smallest and largest elements:
- The function
std::minmax_element
is called with the rangenums.begin()
andnums.end()
, along with the custom comparison functionfaulty_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.
- The function
- Handle exceptions:
Use try-catch block.- If
faulty_compare
throws astd::runtime_error
, thecatch
block captures the exception. - The exception message is displayed using
std::cerr
.
- If
- Display the results:
- If no exception occurs and the range is valid (i.e.,
result.first != nums.end()
andresult.second != nums.end()
):- The smallest element is accessed using
*result.first
and displayed. - The largest element is accessed using
*result.second
and displayed.
- The smallest element is accessed using
- If the range is empty, the program outputs
"The range is empty."
.
- If no exception occurs and the range is valid (i.e.,
Output:
Exception caught: Comparison involving 40 is not allowed.