std::adjacent_find
来自cppreference.com
该页由英文版wiki使用Google Translate机器翻译而来。
该翻译可能存在错误或用词不当。鼠标停留在文本上可以看到原版本。你可以帮助我们修正错误或改进翻译。参见说明请点击这里. |
在头文件 <algorithm> 中定义
|
||
template< class ForwardIt > ForwardIt adjacent_find( ForwardIt first, ForwardIt last ); |
(1) | |
template< class ForwardIt, BinaryPredicate p > ForwardIt adjacent_find( ForwardIt first, ForwardIt last, BinaryPredicate p ); |
(2) | |
搜索范围
[first, last)
为两个连续的相同元素。的第一个版本使用operator==
比较的元素,第二个版本使用给定的二元谓词p
. 原文:
Searches the range
[first, last)
for two consecutive identical elements. The first version uses operator==
to compare the elements, the second version uses the given binary predicate p
. 目录 |
[编辑] 参数
first, last | - | 检查的元素
|
p | - | binary predicate which returns true if the elements should be treated as equal. The signature of the predicate function should be equivalent to the following: bool pred(const Type1 &a, const Type2 &b); The signature does not need to have const &, but the function must not modify the objects passed to it. |
类型要求 | ||
-ForwardIt 必须满足 ForwardIterator 的要求。
|
[编辑] 返回值
一个迭代器相同的元素。如果没有这样的元素被发现,
last
返回原文:
an iterator to the first of the identical elements. If no such elements are found,
last
is returned[编辑] 复杂度
完全
(result - first)
和小((last - 1) - first)
应用的返回值是的谓词在那里,result
.原文:
Exactly the smaller of
(result - first)
and ((last - 1) - first)
applications of the predicate where result
is the return value.[编辑] 可能的实现
版本一 |
---|
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; } |
版本二 |
template<class ForwardIt, BinaryPredicate p> ForwardIt adjacent_find(ForwardIt first, ForwardIt last, BinaryPredicate p) { if (first == last) { return last; } ForwardIt next = first; ++next; for (next != last; ++next, ++first) { if (p(*first, *next)) { return first; } } return last; } |
[编辑] 示例
下面的代码是找到一个对等效的整数的数组intergers .
原文:
The following code finds a pair of equivalent integers in an array of intergers.
#include <algorithm> #include <iostream> int main() { std::vector<int> v1{0, 1, 2, 3, 40, 40, 5}; std::vector<int>::iterator result; result = std::adjacent_find(v1.begin(), v1.end()); if (result == v1.end()) { std::cout << "no matching adjacent elements"; } else { std::cout << "match at: " << std::distance(v1.begin(), result); } }
输出:
match at: 4
[编辑] 另请参阅
删除区间内连续重复的元素 (函数模板) |