std::adjacent_find用于查找容器中第一对相邻相等元素,返回指向首元素的迭代器;未找到则返回end(),适用于vector、list、array等支持前向迭代器的容器。

std::adjacent_find 用来在容器中找第一对相邻且相等的元素,返回指向第一个元素的迭代器;如果没找到,返回尾迭代器(如 end())。
适用于所有支持前向迭代器的容器(vector、list、array 等),默认用 operator== 比较:
end()
std::vector<int> v = {1, 2, 3, 3, 4, 5};
auto it = std::adjacent_find(v.begin(), v.end());
if (it != v.end()) {
std::cout << "重复起始位置: " << std::distance(v.begin(), it)
<< ", 值为 " << *it << "\n"; // 输出:位置 2,值为 3
}第二个参数可传入二元谓词,用于自定义“相邻是否满足条件”:
a, b),返回 true 表示“匹配”std::vector<int> v = {5, 8, 20, 22, 35};
auto it = std::adjacent_find(v.begin(), v.end(),
[](int a, int b) { return b - a > 10; });
// 找到 (8, 20),it 指向 8该算法要求至少两个元素才可能有“相邻对”,内部会自动处理:
立即学习“C++免费学习笔记(深入)”;
end()
last - first - 1 次常和 std::distance、范围 for 或 erase 连用:
std::distance(begin(), it)
v.erase(it, it + 2)(确保 it + 2 有效)it + 1 开始)以上就是c++++的std::adjacent_find算法怎么用 查找容器中的相邻重复元素【STL算法】的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号