目 录CONTENT

文章目录

C++ STL:算法概览

TalentQ
2025-08-28 / 0 评论 / 0 点赞 / 19 阅读 / 0 字

引言

C++ STL(Standard Template Library,标准模板库)中的算法非常丰富,主要定义在 <algorithm> 头文件中。STL 的算法分为几大类,常见的有非变动算法、变动算法、排序与相关算法、集合算法、数值算法等。下面给出主要算法的分类和常用算法列表。

1 非变动算法(不会修改容器内容)

  • for_each:对区间内每个元素执行指定操作

  • find、find_if、find_if_not、find_end、find_first_of

  • count、count_if

  • equal

  • mismatch

  • search、search_n

  • all_of、any_of、none_of

2 变动算法(可能修改容器内容)

  • copy、copy_if、copy_n

  • move

  • swap、swap_ranges

  • fill、fill_n

  • transform

  • replace、replace_if、replace_copy、replace_copy_if

  • remove、remove_if、remove_copy、remove_copy_if

  • unique、unique_copy

  • reverse、reverse_copy

  • rotate、rotate_copy

  • partition、partition_copy、stable_partition

  • shuffle

  • random_shuffle(C++14 之前)

3 排序与相关算法

  • sort

  • stable_sort

  • partial_sort

  • partial_sort_copy

  • nth_element

  • is_sorted、is_sorted_until

4 集合算法(需有序区间)

  • merge

  • inplace_merge

  • includes

  • set_union

  • set_intersection

  • set_difference

  • set_symmetric_difference

5 数值算法(需 <numeric> 头文件)

  • accumulate

  • iota

  • inner_product

  • adjacent_difference

  • partial_sum

6 其它算法

  • min、max、min_element、max_element

  • lexicographical_compare

  • next_permutation、prev_permutation

  • binary_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;
}

0

评论区