Cpp-standard-library-cpp-algorithm-adjacent-find-pred

提供:Dev Guides
移動先:案内検索

C ++アルゴリズムライブラリ-nearest_find()関数

説明

C ++関数* std
algorithm :: adjacent_find()*は、同一の2つの連続する要素の最初の出現を検出し、同一の要素が連続して存在する場合は最初の要素を指す反復子を返し、そうでない場合は最後の要素を指す反復子を返します。

宣言

以下は、std
algorithmヘッダーからのstd :: algorithm :: adjacent_find()関数の宣言です。
template <class ForwardIterator, class BinaryPredicate>
ForwardIterator adjacent_find(ForwardIterator first, ForwardIterator last, BinaryPredicate pred);

パラメーター

  • first -イテレータを検索されたシーケンスの初期位置に転送します。
  • last -検索されたシーケンスの最終位置に反復子を転送します。
  • pred -これは2つの引数を取り、 `+ 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