在 C++ STL中,min_element
和 max_element
是两个非常实用的算法函数,用于快速找到容器或范围内的最小值和最大值,这里以min为例。
头文件:<algorithm>
语法:
template <class ForwardIterator>
ForwardIterator min_element(ForwardIterator first, ForwardIterator last);
template <class ForwardIterator, class Compare>
ForwardIterator min_element(ForwardIterator first, ForwardIterator last, Compare comp);
参数:
first
和last
:定义要搜索的范围[first, last)
。comp
(可选):自定义比较函数,用于指定排序规则。
时间复杂度为
O
(
n
)
O(n)
O(n),其中
n
n
n 是范围 [first, last)
中的元素数量。空间复杂度为
O
(
1
)
O(1)
O(1),因为只使用常量级别的额外空间。
基本用法
如何使用 min_element
和 max_element
找到数组中的最小值和最大值。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {4, 2, 9, 1, 7, 3};
auto min_it = min_element(nums.begin(), nums.end());
auto max_it = max_element(nums.begin(), nums.end());
if (min_it != nums.end()) {
cout << "Min: " << *min_it << endl;
}
if (max_it != nums.end()) {
cout << "Max: " << *max_it << endl;
}
return 0;
}
Min: 1
Max: 9
自定义比较函数
按绝对值大小来寻找最小值。
#include <iostream>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
int main() {
vector<int> nums = {-4, 2, -9, 1, 7, -3};
auto min_it = min_element(nums.begin(), nums.end(), [](int a, int b) {
return abs(a) < abs(b);
});
if (min_it != nums.end()) {
cout << "Min value by absolute value: " << *min_it << endl;
}
return 0;
}
Min value by absolute value: 1
同时查找最小值和最大值
如果需要同时查找最小值和最大值,可以结合 minmax_element
使用(这是 min_element
和 max_element
的扩展版本)。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
vector<int> nums = {4, 2, 9, 1, 7, 3};
auto [min_it, max_it] = minmax_element(nums.begin(), nums.end());
if (min_it != nums.end() && max_it != nums.end()) {
cout << "Minimum value: " << *min_it << endl;
cout << "Maximum value: " << *max_it << endl;
}
return 0;
}
输出:
Minimum value: 1
Maximum value: 9
容器为空的情况
如果范围 [first, last)
为空,则 min_element
和 max_element
返回 last
。因此,在使用返回值之前,应检查容器是否为空。
if (!nums.empty()) {
auto min_it = min_element(nums.begin(), nums.end());
cout << "Min: " << *min_it << endl;
}
自定义cmp
自定义比较函数必须满足严格弱序(strict weak ordering)。简单来说,如果 cmp(a, b)
为真,则 a
应小于 b
。如果 cmp(a, b)
和 cmp(b, a)
都为假,则 a
和 b
相等。