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