目 录CONTENT

文章目录

C++ STL:算法概览

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

引言

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

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

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

  • findfind_iffind_if_notfind_endfind_first_of

  • countcount_if

  • equal

  • mismatch

  • searchsearch_n

  • all_ofany_ofnone_of

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

  • copycopy_ifcopy_n

  • move

  • swapswap_ranges

  • fillfill_n

  • transform

  • replacereplace_ifreplace_copyreplace_copy_if

  • removeremove_ifremove_copyremove_copy_if

  • uniqueunique_copy

  • reversereverse_copy

  • rotaterotate_copy

  • partitionpartition_copystable_partition

  • shuffle

  • random_shuffle(C++14 之前)

3 排序与相关算法

  • sort

  • stable_sort

  • partial_sort

  • partial_sort_copy

  • nth_element

  • is_sortedis_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 其它算法

  • minmaxmin_elementmax_element

  • lexicographical_compare

  • next_permutationprev_permutation

  • binary_searchlower_boundupper_boundequal_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

评论区