Home C&C++函数库 c++ 语法 程序源码 Linux C库

std::

adjacent_find

函数模板  <algorithm>
equality (1)
template <class ForwardIterator>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last);
predicate(2)
template <class ForwardIterator, class BinaryPredicate>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last,
                                  BinaryPredicate pred);

找出范围内相等的相邻元素

搜索范围[first,last],查找第一次出现匹配的两个连续元素, 并返回指向这两个元素中第一个元素的迭代器,如果没有找到这样的一对, 则返回指向最后一个元素的迭代器。
如果两个元素使用operator==(或者在版本(2)中使用pred)比较相等,则它们匹配。

这个函数模板的行为相当于:
template <class ForwardIterator>
   ForwardIterator adjacent_find (ForwardIterator first, ForwardIterator last)
{
  if (first != last)
  {
    ForwardIterator next=first; ++next;
    while (next != last) {
      if (*first == *next)     // or: if (pred(*first,*next)), for version (2)
        return first;
      ++first; ++next;
    }
  }
  return last;
}

☲  参数


first, last
指向序列初始和最终位置的前向迭代器。使用的范围是[first,last], 它包含first和last之间的所有元素,包括first指向的元素,但不包括last指向的元素。
pred
接受两个元素作为参数并返回可转换为bool的值的二元函数。 返回值指示元素在此函数当前环境中是否被认为匹配。
函数不能修改它的任何参数。
它可以是函数指针,也可以是函数对象。

☉  返回值



指向[first,last]范围内第一对连续元素的第一个元素的迭代器。
如果没有匹配的元素对,函数返回last。

☣  示例



// adjacent_find example
#include <iostream>     // std::cout
#include <algorithm>    // std::adjacent_find
#include <vector>       // std::vector

bool myfunction (int i, int j) {
  return (i==j);
}

int main () {
  int myints[] = {5,20,5,30,30,20,10,10,20};
  std::vector<int> myvector (myints,myints+8);
  std::vector<int>::iterator it;

  // using default comparison:
  it = std::adjacent_find (myvector.begin(), myvector.end());

  if (it!=myvector.end())
    std::cout << "the first pair of repeated elements are: " << *it << '\n';

  //using predicate comparison:
  it = std::adjacent_find (++it, myvector.end(), myfunction);

  if (it!=myvector.end())
    std::cout << "the second pair of repeated elements are: " << *it << '\n';

  return 0;
}

输出:
the first pair of repeated elements are: 30
the second pair of repeated elements are: 10

✥ 复杂度



在first 和last之间的distance达到线性:比较元素,直到找到匹配。

⇄ 数据竞争


[first,last)范围内的部分(或全部)对象被访问(最多一次)。

☂ 异常安全性



如果任何元素比较(或pred)或迭代器上的任何操作抛出,则抛出。
注意,无效的参数会导致未定义的行为。

🍄  另请参阅



unique 删除范围内连续的重复项(函数模板)
find 在范围内查找值(函数模板)
find_if 在范围内查找元素(函数模板)

联系我们 免责声明 关于CandCplus 网站地图