To find the smallest and largest elements in a range in C++, you can use the std::min_element()
and std::max_element()
algorithms from the <algorithm>
 header.
These functions are efficient and straightforward, operating in linear time.
The std::min_element()
function returns an iterator to the smallest element in the range [first, last)
.
Here’s an example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers{3, 1, 4, 1, 5, 9};
auto min_it = std::min_element(
numbers.begin(), numbers.end());
if (min_it != numbers.end()) {
std::cout << "The smallest element is "
<< *min_it;
}
}
The smallest element is 1
Similarly, the std::max_element()
function returns an iterator to the largest element in the range [first, last)
.
Here’s an example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> numbers{3, 1, 4, 1, 5, 9};
auto max_it = std::max_element(
numbers.begin(), numbers.end());
if (max_it != numbers.end()) {
std::cout << "The largest element is "
<< *max_it;
}
}
The largest element is 9
You can find both the smallest and largest elements in a single pass using std::minmax_element()
.
This function returns a pair of iterators: the first points to the smallest element, and the second points to the largest element.
Here’s an example:
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> nums{3, 1, 4, 1, 5, 9};
auto [min_it, max_it] = std::minmax_element(
nums.begin(), nums.end());
if (min_it != nums.end() && max_it != nums.end()) {
std::cout << "The smallest element is "
<< *min_it << "\n";
std::cout << "The largest element is "
<< *max_it << "\n";
}
}
The smallest element is 1
The largest element is 9
[first, last)
is valid and non-empty before calling these functions.std::min_element()
, std::max_element()
, and std::minmax_element()
if you need to define a specific order.Using std::min_element()
, std::max_element()
, and std::minmax_element()
provides an efficient and clear way to find the smallest and largest elements in a range.
These algorithms are part of the standard library, making them both reliable and easy to use in a wide variety of contexts.
Answers to questions are automatically generated and may not have been reviewed.
An introduction to iterator and range-based algorithms, using examples from the standard library