function template
<algorithm>

std::adjacent_find

相等 (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) 中搜索第一個出現的兩個連續相等的元素,並返回指向這兩個元素中第一個元素的迭代器,如果未找到這樣的對,則返回 last

如果使用 operator==(或在版本(2)中使用 pred)進行比較,則兩個元素匹配。

此函式模板的行為等同於
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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
Forward 迭代器,指向被搜尋序列的初始和最終位置。使用的範圍是 [first,last),它包含 firstlast 之間的所有元素,包括 first 指向的元素,但不包括 last 指向的元素。
pred
二進位制函式,接受兩個元素作為引數,並返回一個可轉換為 bool 的值。返回的值指示在函式上下文中元素是否被視為匹配。
該函式不得修改其任何引數。
這可以是一個函式指標或函式物件。

返回值

指向範圍 [first,last) 中第一個匹配的連續元素對的第一個元素的迭代器。
如果未找到這樣的對,函式將返回 last

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// 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


複雜度

最多與 firstlast 之間的 距離 成線性關係:比較元素直到找到匹配項。

資料競爭

範圍 [first,last) 中的一些(或全部)物件被訪問(最多一次)。

異常

如果任何元素比較(或pred)丟擲異常,或者任何迭代器操作丟擲異常,則丟擲異常。
請注意,無效引數會導致未定義行為

另見