簡単なプログラム解釈C++STLアルゴリズムシリーズの4:adjacent_find
C++STLの非可変アルゴリズム(Non-mutating algorithms)は、操作データを破壊しないテンプレート関数のセットであり、シーケンスデータの個々の処理、要素検索、サブシーケンス検索、統計、マッチングを行うために使用される.
adjacent_findアルゴリズムは、等しいまたは条件を満たす隣接要素ペアを検索するために使用される.2つの関数プロトタイプがあります.1つは、反復器区間[first,last]で2つの連続する要素が等しい場合に、要素ペアの最初の要素の反復器位置を返します.もう1つは、2元述語を使用してbinary_predを判断し、反復器区間[first,last)でbinary_pred条件を満たす隣接要素ペアを検索し、見つからない場合にlastを返します.
関数のプロトタイプ:
サンプルコード:
*******************************************************************************************************************************
C++経典書目索引及び資源ダウンロード:http://blog.csdn.net/jerryjbiao/article/details/7358796
********************************************************************************************************************************
adjacent_findアルゴリズムは、等しいまたは条件を満たす隣接要素ペアを検索するために使用される.2つの関数プロトタイプがあります.1つは、反復器区間[first,last]で2つの連続する要素が等しい場合に、要素ペアの最初の要素の反復器位置を返します.もう1つは、2元述語を使用してbinary_predを判断し、反復器区間[first,last)でbinary_pred条件を満たす隣接要素ペアを検索し、見つからない場合にlastを返します.
関数のプロトタイプ:
template<class ForwardIterator>
ForwardIterator adjacent_find(
ForwardIterator _First,
ForwardIterator _Last
);
template<class ForwardIterator , class BinaryPredicate>
ForwardIterator adjacent_find(
ForwardIterator _First,
ForwardIterator _Last,
BinaryPredicate _Comp
);
サンプルコード:
/*******************************************************************
* Copyright (C) Jerry Jiang
* File Name : adjacent_find.cpp
* Author : Jerry Jiang
* Create Time : 2011-9-30 22:07:22
* Mail : [email protected]
* Blog : http://blog.csdn.net/jerryjbiao
* Description : C++ STL
* : adjacent_find
******************************************************************/
#include <algorithm>
#include <list>
#include <iostream>
using namespace std;
// X y
bool parity_equal(int x, int y)
{
return (x - y) % 2 == 0 ? 1 : 0;
}
int main()
{
//
list<int> iList;
iList.push_back(3);
iList.push_back(6);
iList.push_back(9);
iList.push_back(11);
iList.push_back(11);
iList.push_back(18);
iList.push_back(20);
iList.push_back(20);
//
list<int>::iterator iter;
for(iter = iList.begin(); iter != iList.end(); ++iter)
{
cout << *iter << " ";
}
cout << endl;
//
list<int>::iterator iResult = adjacent_find(iList.begin(), iList.end());
if (iResult != iList.end())
{
cout << " :" << endl;
cout << *iResult++ << endl;
cout << *iResult << endl;
}
//
iResult = adjacent_find(iList.begin(), iList.end(), parity_equal);
if (iResult != iList.end())
{
cout << " :" << endl;
cout << *iResult++ << endl;
cout << *iResult << endl;
}
return 0;
}
*******************************************************************************************************************************
C++経典書目索引及び資源ダウンロード:http://blog.csdn.net/jerryjbiao/article/details/7358796
********************************************************************************************************************************