algorithm::adjacent_find()
描述 (Description)
C ++函数std::algorithm::adjacent_find()查找第一次出现两个相同的连续元素,如果相同元素连续存在则返回指向第一个元素的迭代器,否则返回指向最后一个元素的迭代器。
声明 (Declaration)
以下是std :: algorithm :: adjacent_find()函数形式std :: algorithm头的声明。
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred);
参数 (Parameters)
first - 将迭代器转发到搜索序列的初始位置。
last - 将迭代器转发到搜索序列的最终位置。
pred - 这是一个函数,它接受两个参数并返回bool 。
返回值
如果相同元素连续存在,则返回指向第一个元素的迭代器,否则返回指向最后一个元素的迭代器。
异常 (Exceptions)
如果任何元素比较对象抛出异常,则抛出异常。
请注意,无效参数会导致未定义的行为。
时间复杂
在第一个和最后一个之间的距离线性。
例子 (Example)
以下示例显示了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