引言
C++ STL(Standard Template Library,标准模板库)中的算法非常丰富,主要定义在 <algorithm> 头文件中。STL 的算法分为几大类,常见的有非变动算法、变动算法、排序与相关算法、集合算法、数值算法等。下面给出主要算法的分类和常用算法列表。
1 非变动算法(不会修改容器内容)
for_each:对区间内每个元素执行指定操作find、find_if、find_if_not、find_end、find_first_ofcount、count_ifequalmismatchsearch、search_nall_of、any_of、none_of
2 变动算法(可能修改容器内容)
copy、copy_if、copy_nmoveswap、swap_rangesfill、fill_ntransformreplace、replace_if、replace_copy、replace_copy_ifremove、remove_if、remove_copy、remove_copy_ifunique、unique_copyreverse、reverse_copyrotate、rotate_copypartition、partition_copy、stable_partitionshufflerandom_shuffle(C++14 之前)
3 排序与相关算法
sortstable_sortpartial_sortpartial_sort_copynth_elementis_sorted、is_sorted_until
4 集合算法(需有序区间)
mergeinplace_mergeincludesset_unionset_intersectionset_differenceset_symmetric_difference
5 数值算法(需 <numeric> 头文件)
accumulateiotainner_productadjacent_differencepartial_sum
6 其它算法
min、max、min_element、max_elementlexicographical_comparenext_permutation、prev_permutationbinary_search、lower_bound、upper_bound、equal_range
示例代码
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main() {
vector<int> v = {1, 2, 3, 4, 5};
// 查找
auto it = find(v.begin(), v.end(), 3);
if (it != v.end()) cout << "Found 3" << endl;
// 排序
sort(v.begin(), v.end(), greater<int>());
// 累加
int sum = accumulate(v.begin(), v.end(), 0);
cout << "Sum: " << sum << endl;
}
评论区