常用算法函数
STL提供了大量的算法模板,可以用于各种容器,无需重复造轮子。
#include <algorithm>
using namespace std;
int main() {
vector v = {5, 2, 8, 1, 9, 3};
// 升序排序
sort(v.begin(), v.end());
// v: {1, 2, 3, 5, 8, 9}
// 降序排序
sort(v.begin(), v.end(), greater());
// v: {9, 8, 5, 3, 2, 1}
// 自定义排序
sort(v.begin(), v.end(), [](int a, int b) {
return a % 2 < b % 2; // 偶数在前,奇数在后
});
// 排序数组
int arr[] = {5, 2, 8, 1};
sort(arr, arr + 4);
return 0;
}
struct Student {
string name;
int score;
};
// 按分数排序,分数相同保持原有顺序
vector students = {
{"Alice", 85},
{"Bob", 92},
{"Charlie", 85}
};
stable_sort(students.begin(), students.end(),
[](const Student& a, const Student& b) {
return a.score < b.score;
});
// Alice 和 Charlie 分数相同,但 Alice 仍在前面
vector v = {5, 2, 8, 1, 9, 3, 7, 4, 6};
// 找到第3小的元素,并使它前面的元素都小于它
// 时间复杂度 O(n),比 sort 快
nth_element(v.begin(), v.begin() + 2, v.end());
// 前3个元素是整个数组中最小的3个(顺序可能不同)
vector v = {1, 3, 5, 7, 9};
auto it = find(v.begin(), v.end(), 5);
if (it != v.end()) {
cout << "找到 5,位置: " << distance(v.begin(), it) << endl;
}
// 查找不存在的元素
it = find(v.begin(), v.end(), 4);
if (it == v.end()) {
cout << "未找到 4" << endl;
}
vector v = {1, 3, 5, 7, 9};
// 查找元素是否存在(需要有序)
if (binary_search(v.begin(), v.end(), 5)) {
cout << "找到 5" << endl;
}
// lower_bound - 大于等于x的第一个元素
auto it = lower_bound(v.begin(), v.end(), 5);
// it 指向 5
// upper_bound - 大于x的第一个元素
it = upper_bound(v.begin(), v.end(), 5);
// it 指向 7
vector v = {1, 2, 2, 3, 3, 3, 4};
int cnt = count(v.begin(), v.end(), 3);
cout << "3 出现了 " << cnt << " 次" << endl;
// count_if - 统计满足条件的元素
int odd = count_if(v.begin(), v.end(), [](int x) {
return x % 2 == 1;
});
cout << "奇数有 " << odd << " 个" << endl;
#include <numeric>
vector v = {1, 2, 3, 4, 5};
// 求和
int sum = accumulate(v.begin(), v.end(), 0);
cout << sum << endl; // 15
// 初始值为10
int sum2 = accumulate(v.begin(), v.end(), 10);
cout << sum2 << endl; // 25
// 求积
int product = accumulate(v.begin(), v.end(), 1, multiplies());
cout << product << endl; // 120
copy - 复制
fill - 填充
reverse - 反转
unique - 去重
set_union - 并集
set_intersection - 交集
set_difference - 差集
next_permutation - 下一个排列
lower_bound / upper_bound - 二分查找边界