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_elementfunction.<vector>is included for thestd::vectorcontainer.
- Initialize a vector:
- A vector named
numsis created and initialized with the elements{10, 20, 5, 40, 15}.
- A vector named
- Find the smallest and largest elements:
- The function
std::minmax_elementis 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.firstandresult.secondare 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.firstand displayed. - The largest element is accessed using
*result.secondand 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_comparetakes two integers,aandb, as input. - It compares the absolute values of the two integers using
std::abs. - It returns
trueif the absolute value ofais less than that ofb, andfalseotherwise.
- The function
- Initialize a vector:
- A vector named
numsis 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_elementis called with the rangenums.begin()andnums.end(), and the custom comparison functionabs_compareis 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.firstandresult.secondare 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_compareis a custom function that compares two integers,aandb.- The function throws a
std::runtime_errorexception if eitheraorbequals40, with the message"Comparison involving 40 is not allowed.". - If no exception is thrown, the function compares
aandband returnstrueifais less thanb, andfalseotherwise.
- Attempt to find the smallest and largest elements:
- The function
std::minmax_elementis 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_comparethrows astd::runtime_error, thecatchblock 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.firstand displayed. - The largest element is accessed using
*result.secondand 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.
