目录

algorithm::adjacent_find()

描述 (Description)

C ++函数std::algorithm::adjacent_find()查找第一次出现两个相同的连续元素,如果相同元素连续存在则返回指向第一个元素的迭代器,否则返回指向最后一个元素的迭代器。

声明 (Declaration)

以下是std :: algorithm :: adjacent_find()函数形式std :: algorithm头的声明。

C++98

template <class ForwardIterator>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last);

参数 (Parameters)

  • first - 将迭代器转发到搜索序列的初始位置。

  • last - 将迭代器转发到搜索序列的最终位置。

返回值

如果相同元素连续存在,则返回指向第一个元素的迭代器,否则返回指向最后一个元素的迭代器。

异常 (Exceptions)

如果任何元素比较对象抛出异常,则抛出异常。

请注意,无效参数会导致未定义的行为。

时间复杂

第一个最后一个之间的距离线性。

例子 (Example)

以下示例显示了std :: algorithm :: adjacent_find()函数的用法。

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void) {
   vector<int> v = {1, 2, 3, 3, 5};
   auto it = adjacent_find(v.begin(), v.end());
   if (it != v.end())
      cout << "First occurrence of consecutive identical element = " << *it << endl;
   v[3] = 4;
   it = adjacent_find(v.begin(), v.end());
   if (it == v.end())
      cout << "There are no cosecutive identical elemens" << endl;
   return 0;
}

让我们编译并运行上面的程序,这将产生以下结果 -

First occurrence of consecutive identical element = 3
There are no cosecutive identical elemens
↑回到顶部↑
WIKI教程 @2018