std::adjacent_find
在标头 <algorithm> 定义 | ||
template<class ForwardIt > ForwardIt adjacent_find( ForwardIt first, ForwardIt last ); | (1) | (C++20 起为 constexpr ) |
template<class ExecutionPolicy, class ForwardIt > ForwardIt adjacent_find( ExecutionPolicy&& policy, | (2) | (C++17 起) |
template<class ForwardIt, class BinaryPred > ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPred p ); | (3) | (C++20 起为 constexpr ) |
template<class ExecutionPolicy, class ForwardIt, class BinaryPred > ForwardIt adjacent_find( ExecutionPolicy&& policy, | (4) | (C++17 起) |
在范围 [
first,
last)
中搜索两个连续的相等元素。
std::is_execution_policy_v<std::decay_t<ExecutionPolicy>> 是 true。 | (C++20 前) |
std::is_execution_policy_v<std::remove_cvref_t<ExecutionPolicy>> 是 true。 | (C++20 起) |
目录 |
[编辑]参数
first, last | - | 要检验的元素范围的迭代器对 |
policy | - | 所用的执行策略 |
p | - | 若元素应被当做相等则返回 true 的二元谓词 谓词函数的签名应等价于如下: bool pred(const Type1 &a, const Type2 &b); 虽然签名不必有 const& ,函数也不能修改传递给它的对象,而且必须接受(可为 const 的)类型 |
类型要求 | ||
-ForwardIt 必须满足老式向前迭代器(LegacyForwardIterator) 。 | ||
-BinaryPred 必须满足二元谓词(BinaryPredicate) 。 |
[编辑]返回值
指向首对等同元素的首个元素的迭代器,即首个满足 *it ==*(it +1)(版本 (1,2))或 p(*it, *(it +1))!=false(版本 (3,4))的迭代器 it。
如果找不到这种元素,那么返回 last。
[编辑]复杂度
给定 result 为 adjacent_find
的返回值,M 为 std::distance(first, result),N 为 std::distance(first, last):
[编辑]异常
拥有名为 ExecutionPolicy
的模板形参的重载按下列方式报告错误:
- 如果作为算法一部分调用的函数的执行抛出异常,且
ExecutionPolicy
是标准策略之一,那么调用 std::terminate。对于任何其他ExecutionPolicy
,行为由实现定义。 - 如果算法无法分配内存,那么抛出 std::bad_alloc。
[编辑]可能的实现
adjacent_find (1) |
---|
template<class ForwardIt> ForwardIt adjacent_find(ForwardIt first, ForwardIt last){if(first == last)return last; ForwardIt next = first;++next; for(; next != last;++next, ++first)if(*first ==*next)return first; return last;} |
adjacent_find (3) |
template<class ForwardIt, class BinaryPred> ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPred p){if(first == last)return last; ForwardIt next = first;++next; for(; next != last;++next, ++first)if(p(*first, *next))return first; return last;} |
[编辑]示例
#include <algorithm>#include <functional>#include <iostream>#include <vector> int main(){std::vector<int> v1{0, 1, 2, 3, 40, 40, 41, 41, 5}; auto i1 = std::adjacent_find(v1.begin(), v1.end()); if(i1 == v1.end())std::cout<<"没有匹配的相邻元素\n";elsestd::cout<<"第一对相等的相邻元素位于 "<<std::distance(v1.begin(), i1)<<",*i1 = "<<*i1 <<'\n'; auto i2 = std::adjacent_find(v1.begin(), v1.end(), std::greater<int>());if(i2 == v1.end())std::cout<<"整个 vector 已经是升序的\n";elsestd::cout<<"非降序子序列中最后的元素位于 "<<std::distance(v1.begin(), i2)<<",*i2 = "<<*i2 <<'\n';}
输出:
第一对相等的相邻元素位于 4,*i1 = 40 非降序子序列中最后的元素位于 7,*i2 = 41
[编辑]缺陷报告
下列更改行为的缺陷报告追溯地应用于以前出版的 C++ 标准。
缺陷报告 | 应用于 | 出版时的行为 | 正确行为 |
---|---|---|---|
LWG 240 | C++98 | (1,3) 中谓词会应用 std::find(first, last, value)- first 次,但 value 没有定义 | 应用 std::min((result - first) +1, (last - first)-1) 次 |
[编辑]参阅
移除范围中连续重复元素 (函数模板) | |
(C++20) | 查找首对相同(或满足给定谓词)的相邻元素 (算法函数对象) |