STL_算法_查找算法(adjacent_find)

C++ Primer 學習中。。。

 

簡單記錄下我的學習過程 (代碼爲主)


adjacent_find         //用來查找連續兩個相等的或者符合方法的



#include<iostream>
#include<cstdio>
#include<string>
#include <vector>
#include<algorithm>
using namespace std;

/*****************************************
//所有容器適用(線性的)
adjacent_find(b,e);
adjacent_find(b,e,p);
用來查找連續兩個相等的或者符合方法的

如果是已序區間
則選用已序區間查找算法
binary_search()
includes()
lower_bound()
upper_bound()
*****************************************/


/*************************************************************************************
std::adjacent_find()           所有容器適用                                algorithm
--------------------------------------------------------------------------------------
template <class ForwardIterator>
   ForwardIterator adjacent_find ( ForwardIterator first, ForwardIterator last );

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

//eg:
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 the pred version
                return first;
            else{++first;++next;}
        }
    }
    return last;
}
*************************************************************************************/
bool myfunction (int i, int j)
{
    return (i==j*2);
}
int main()
{
    int myints[] = {10,20,30,30,40,20,10,20};

    vector<int> myvector (myints,myints+8);
    vector<int>::iterator it;

    for(it=myvector.begin();it!=myvector.end();++it)
        cout<<*it<<" ";
    cout<<endl;

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

    if (it!=myvector.end())
        cout << "the first consecutive repeated elements are: " << *it << endl;

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

    if (it!=myvector.end())
        cout << "the second consecutive repeated elements are: " << *it << endl;

    return 0;
}
/*****
Output
    10 20 30 30 40 20 10 20
    the first consecutive repeated elements are: 30
    the second consecutive repeated elements are: 40
*/

發佈了294 篇原創文章 · 獲贊 45 · 訪問量 37萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章