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
| 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 the minimum. Defaults to <. |
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:
- We initialized a vector named
numswith the elements{10, 20, 5, 40, 15}. - The
std::min_elementfunction is used to find the smallest element in the range[nums.begin(), nums.end()). It returns an iterator pointing to the smallest element. - A conditional check is performed to verify if the iterator returned by
std::min_elementis not equal tonums.end(). If true, it means the range is not empty, and the smallest element can be accessed using*it. - The smallest element is printed to the console using
std::cout. - 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:
- We defined a custom comparison function named
abs_compare. This function compares the absolute values of two integers usingstd::abs. - We initialized a vector named
numswith the elements{-10, 20, -5, 40, -15}, which include both positive and negative values. - The
std::min_elementfunction is used with three arguments:nums.begin(),nums.end(), and the custom comparison functionabs_compare. It finds the smallest element in the range based on its absolute value. - A conditional check is performed to ensure that the iterator returned by
std::min_elementis not equal tonums.end(). If true, it means the range is not empty, and the smallest element (by absolute value) can be accessed using*it. - 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:
- We defined a custom comparison function named
faulty_compare. This function throws astd::runtime_errorexception if either of the integers being compared is5. Otherwise, it compares the integers in ascending order. - We initialized a vector named
numswith the elements{10, 20, 5, 40, 15}. - A
tryblock is used to safely execute thestd::min_elementfunction, anticipating potential exceptions from the custom comparison function. - The
std::min_elementfunction is called with three arguments:nums.begin(),nums.end(), and the custom comparison functionfaulty_compare. It attempts to find the smallest element in the range based on the comparison logic. - During execution, when
faulty_compareencounters the value5, it throws astd::runtime_error, halting further comparisons. - The
catchblock captures the exception and prints an error message to the console usingstd::cerr, explaining the cause of the exception. - If no exception were thrown, the program would check if the iterator returned by
std::min_elementis not equal tonums.end(). If true, it would print the smallest element. If the range were empty, it would display a message indicating this.
