C++ 的标准模板库(STL)的方法和函数一般位于 algorithm 库,它为程序员提供了一套强大的工具,用于执行各种数据操作,这些操作包括搜索、排序、变换和其他通用算法。这些算法的设计目标是通用性、高效性和灵活性,使得 algorithm 库成为处理数据和实现复杂逻辑的首选工具。本文分为9个大类:非修改算法、修改算法、排序算法、二分查找算法、集合算法、堆算法、最小/最大值算法、数值算法、其他算法等,以下进行分类介绍。
1. 非修改算法
非修改算法用于查询或检索数据,不改变数据内容。
all_of:检查区间内所有元素是否满足给定条件。
any_of:检查区间内是否有元素满足给定条件。
none_of:检查区间内是否所有元素都不满足给定条件。
for_each:对区间内的每个元素应用一个操作。
count:计算区间中等于给定值的元素个数。
count_if:计算区间中满足条件的元素个数。
mismatch:找到两个区间中第一个不相等的元素对。
equal:检查两个区间是否相等。
find:在区间中查找指定值,返回第一个匹配的迭代器。
find_if:查找第一个满足条件的元素。
find_if_not:查找第一个不满足条件的元素。
search:在一个区间内查找子序列。
search_n:查找连续 N 个满足条件的元素。
find_end:查找子序列的最后一次出现。
adjacent_find:查找相邻的相等元素对。
lexicographical_compare:按字典顺序比较两个区间。
#include <algorithm>
#include <vector>
#include <iostream>
#include <iterator>
int main() {
std::vector<int> v = {1, 2, 3, 4, 5, 4, 3, 2, 1};
// all_of
if (std::all_of(v.begin(), v.end(), [](int i){ return i > 0; })) {
std::cout << "All elements are greater than 0.\n";
}
// any_of
if (std::any_of(v.begin(), v.end(), [](int i){ return i == 4; })) {
std::cout << "There is a 4 in the vector.\n";
}
// none_of
if (std::none_of(v.begin(), v.end(), [](int i){ return i < 0; })) {
std::cout << "No elements are less than 0.\n";
}
// for_each
std::cout << "Vector: ";
std::for_each(v.begin(), v.end(), [](const int& n) { std::cout << n << " "; });
std::cout << "\n";
// count
int twos = std::count(v.begin(), v.end(), 2);
std::cout << "Number of twos: " << twos << "\n";
// count_if
int odd_count = std::count_if(v.begin(), v.end(), [](int i){ return i % 2 != 0; });
std::cout << "Number of odd numbers: " << odd_count << "\n";
// find
auto it = std::find(v.begin(), v.end(), 3);
if (it != v.end()) {
std::cout << "Found a 3 at position: " << std::distance(v.begin(), it) << "\n";
}
// find_if
auto it_if = std::find_if(v.begin(), v.end(), [](int i){ return i == 4; });
if (it_if != v.end()) {
std::cout << "Found a 4 at position: " << std::distance(v.begin(), it_if) << "\n";
}
// find_if_not
auto it_if_not = std::find_if_not(v.begin(), v.end(), [](int i){ return i == 4; });
if (it_if_not != v.end()) {
std::cout << "First non-4 found at position: " << std::distance(v.begin(), it_if_not) << "\n";
}
// adjacent_find
auto it_adj = std::adjacent_find(v.begin(), v.end())