STL算法库存于,提供sort、find、binary_search等函数,用于排序、查找和操作容器数据,需用迭代器调用,注意binary_search要求数据有序,配合lambda可定制行为。

STL算法库是C++中非常实用的一部分,位于头文件中。它提供了一系列通用的函数,用于对容器中的数据进行操作,比如排序、查找、修改等。这些算法通常以迭代器作为参数,因此可以和vector、array、list等多种容器配合使用。
1. 排序:sort
sort函数用于对一段范围内的元素进行升序排序,默认使用比较。
- 需要包含头文件:
#include - 调用方式:
std::sort(起始迭代器, 结束迭代器)
示例:
#include#include #include std::vector
nums = {5, 2, 8, 1, 9}; std::sort(nums.begin(), nums.end()); // 升序 // 结果:1 2 5 8 9 std::sort(nums.rbegin(), nums.rend()); // 降序 // 或者使用自定义比较函数 std::sort(nums.begin(), nums.end(), std::greater
());
也可以传入自定义比较函数或lambda表达式:
立即学习“C++免费学习笔记(深入)”;
std::sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b; // 降序
});
2. 查找:find
find用于在指定范围内查找某个值,返回第一个匹配元素的迭代器,若未找到则返回结束迭代器。
基本用法:- 函数原型:
std::find(起始, 结束, 值) - 适用于不保证有序的数据
示例:
#include#include std::vector
nums = {3, 7, 2, 8, 4}; auto it = std::find(nums.begin(), nums.end(), 8); if (it != nums.end()) { std::cout << "找到了,位置:" << (it - nums.begin()) << std::endl; } else { std::cout << "未找到" << std::endl; }
3. 二分查找:binary_search
binary_search用于判断有序序列中是否存在某个值,返回bool类型。
注意:- 必须保证数据已经排序,否则结果未定义
- 只判断存在性,不返回位置
示例:
std::vectornums = {1, 3, 5, 7, 9}; bool found = std::binary_search(nums.begin(), nums.end(), 5); if (found) { std::cout << "5 存在于数组中" << std::endl; }
如果想获取位置,可以结合lower_bound或upper_bound:
auto it = std::lower_bound(nums.begin(), nums.end(), 5);
if (it != nums.end() && *it == 5) {
std::cout << "位置:" << (it - nums.begin()) << std::endl;
}
4. 其他常用算法
STL还提供了许多其他实用函数:
-
reverse:反转区间元素
std::reverse(nums.begin(), nums.end()); -
count:统计某值出现次数
int cnt = std::count(nums.begin(), nums.end(), 5); -
max_element / min_element:获取最大/最小元素的迭代器
auto max_it = std::max_element(nums.begin(), nums.end()); -
unique:去重相邻重复元素(常与erase配合)
nums.erase(std::unique(nums.begin(), nums.end()), nums.end());
基本上就这些常见用法。掌握sort、find、binary_search等函数,能大幅提升编码效率。关键是记得使用前包含,并理解它们对数据顺序的要求。比如binary_search必须用于有序数据,而find没有这个限制。灵活使用lambda和自定义比较函数,可以让算法更强大。不复杂但容易忽略细节。










