C++ Algorithm 库 - adjacent_find() 函数
描述
C++ 函数 std::algorithm::adjacent_find() 查找两个相同的连续元素的第一次出现,如果相同的元素连续存在,则返回指向第一个元素的迭代器,否则返回指向最后一个元素的迭代器。
声明
以下是 std::algorithm::adjacent_find() 函数形式 std::algorithm 头的声明。
template <class ForwardIterator, class BinaryPredicate> ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
参数
first − 将迭代器转发到搜索序列的初始位置。
last − 将迭代器转发到搜索序列的最终位置。
pred − 这是一个接受两个参数并返回 bool 的函数。
返回值
如果相同元素连续存在,则返回指向第一个元素的迭代器,否则返回指向最后一个元素的迭代器。
异常
如果任何元素比较对象抛出异常,则抛出异常。
请注意,无效的参数会导致未定义的行为。
时间复杂度
first 和 last 之间的距离呈线性关系。
示例
以下示例显示了 std::algorithm::adjacent_find() 函数的用法。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
bool predicate(int a, int b) {
return (a == b);
}
int main(void) {
vector<int> v = {1, 2, 3, 3, 4, 5, 5};
auto it = adjacent_find(v.begin(), v.end());
if (it != v.end())
cout << "First occurrence of consecutive identical element = "
<< *it << endl;
it = adjacent_find(++it, v.end(), predicate);
if (it != v.end())
cout << "Second occurrence of consecutive identical element = "
<< *it << endl;
return 0;
}
让我们编译并运行上面的程序,这将产生以下结果 −
First occurrence of consecutive identical element = 3 Second occurrence of consecutive identical element = 5

