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

STL算法库是C++中非常实用的一部分,位于<algorithm>头文件中。它提供了一系列通用的函数,用于对容器中的数据进行操作,比如排序、查找、修改等。这些算法通常以迭代器作为参数,因此可以和vector、array、list等多种容器配合使用。
sort函数用于对一段范围内的元素进行升序排序,默认使用<比较。
#include <algorithm>
std::sort(起始迭代器, 结束迭代器)
示例:
#include <vector>
#include <algorithm>
#include <iostream>
<p>std::vector<int> nums = {5, 2, 8, 1, 9};
std::sort(nums.begin(), nums.end()); // 升序
// 结果:1 2 5 8 9</p><p>std::sort(nums.rbegin(), nums.rend()); // 降序
// 或者使用自定义比较函数
std::sort(nums.begin(), nums.end(), std::greater<int>());</p>也可以传入自定义比较函数或lambda表达式:
立即学习“C++免费学习笔记(深入)”;
std::sort(nums.begin(), nums.end(), [](int a, int b) {
return a > b; // 降序
});
find用于在指定范围内查找某个值,返回第一个匹配元素的迭代器,若未找到则返回结束迭代器。
基本用法:std::find(起始, 结束, 值)
示例:
#include <vector>
#include <algorithm>
<p>std::vector<int> nums = {3, 7, 2, 8, 4};
auto it = std::find(nums.begin(), nums.end(), 8);</p><p>if (it != nums.end()) {
std::cout << "找到了,位置:" << (it - nums.begin()) << std::endl;
} else {
std::cout << "未找到" << std::endl;
}</p>binary_search用于判断有序序列中是否存在某个值,返回bool类型。
注意:示例:
std::vector<int> nums = {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;
}
STL还提供了许多其他实用函数:
std::reverse(nums.begin(), nums.end());
int cnt = std::count(nums.begin(), nums.end(), 5);
auto max_it = std::max_element(nums.begin(), nums.end());
nums.erase(std::unique(nums.begin(), nums.end()), nums.end());
基本上就这些常见用法。掌握sort、find、binary_search等函数,能大幅提升编码效率。关键是记得使用前包含<algorithm>,并理解它们对数据顺序的要求。比如binary_search必须用于有序数据,而find没有这个限制。灵活使用lambda和自定义比较函数,可以让算法更强大。不复杂但容易忽略细节。
以上就是C++中的STL算法库怎么用_C++ sort、find、binary_search等常用算法函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号