4. 算法
C++ 的 STL 库中提供了算法库,它使用泛型编程方法将经典的算法几乎都编辑成为函数模板并高度优化。他能让你用及其简化的代码完成复杂的数据操作。
STL 的算法库在头文件<algorithm> 中声明,使用时需要包含这个头文件。
STL中的算法函数模版
函数模板名
说明
查找操作
all_of(C++11)所有元素都为
true 返回 true ,否则返回 false。any_of(C++11)只要有元素为
true 返回 true ,都为 false 返回 false。find顺序查找。
find_if条件查找
binary_search二分查找(需有序)
count计数
count_if条件计数
mismatch找第一个不匹配位置
equal判断两个区间是否相
复制操作
copy拷贝
copy_if条件拷贝
move移动
交换操作
swap交换
变换操作
transform使用函数替换
replace替换
replace_if条件替换
通用操作
fill填充固定值
generate用函数生成值
移除操作
remove删除
unique去重复
顺序改变操作
reverse本地调换顺序
reverse_copy返回调换顺序的复制品
排序操作
sort排序
stable_sort稳定排序
partial_sort部分排序
具体操作详见官方文档:https://en.cppreference.com/cpp/algorithm
示例:
// filename: algorithm.cpp
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
int main()
{
vector<int> v = {11, 3, 7, 5, 9};
// 查找
auto it = find(v.begin(), v.end(), 5); // 指向5
if (it != v.end())
cout << "finded: " << *it << endl;
// 排序
std::sort(v.begin(), v.end()); // v = {3, 5, 7, 9, 11}
for(auto it = v.begin(); it < v.end(); it++)
cout << *it << " ";
cout << endl;
// 求和(需要 <numeric>)
int sum = std::accumulate(v.begin(), v.end(), 0); // 25
cout << "sum: " << sum << endl;
return 0;
}
编译和运行结果如下:
weimz@mzstudio:~$ g++ -o algorithm algorithm.cpp
weimz@mzstudio:~$ ./algorithm
finded: 5
3 5 7 9 11
sum: 35