STL_算法_查找算法(search_n)

C++ Primer 学习中。。。

 

简单记录下我的学习过程 (代码为主)

 

search_n    //查找连续的n个满足条件的。。

 

#include<iostream>
#include<cstdio>
#include<cstring>
#include<deque>
#include<vector>
#include<algorithm>
using namespace std;
/*************************************************************************************
std::search_n           所有容器适用                                       algorithm
--------------------------------------------------------------------------------------
template <class ForwardIterator, class Size, class T>
ForwardIterator search_n ( ForwardIterator first, ForwardIterator last,
                           Size count, const T& value );

template <class ForwardIterator, class Size, class T, class BinaryPredicate>
ForwardIterator search_n ( ForwardIterator first, ForwardIterator last,
                           Size count, const T& value, BinaryPredicate pred );


eg:
template<class ForwardIterator, class Size, class T>
ForwardIterator search_n ( ForwardIterator first, ForwardIterator last,
                           Size count, const T& value )
{
    ForwardIterator it, limit;
    Size i;

    limit=first;
    advance(limit,distance(first,last)-count);

    while (first!=limit)
    {
        it = first;
        i=0;
        while (*it==value)       // or: while (pred(*it,value)) for the pred version
        {
            ++it;
            if (++i==count) return first;
        }
        ++first;
    }
    return last;
}
**************************************************************************************/


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

int main ()
{
    int myints[]= {10,20,30,30,20,10,10,10,20};
    vector<int> myvector (myints,myints+9);

    vector<int>::iterator it;

    // using default comparison:
    /*** search_n(s,e,cnt,num);找区间内[s,e)连续cnt个的num 返回的是找到的第一个num的迭代器***/
    it = search_n (myvector.begin(), myvector.end(), 2, 30);

    if (it!=myvector.end())
        cout << "two 30s found at position " << int(it-myvector.begin()) << endl;
    else
        cout << "match not found" << endl;

    // using predicate comparison:
    /*** search_n(s,e,cnt,num,cmp);找区间内[s,e)连续cnt个的num符合cmp()条件的,返回的是找到的第一个num的迭代器***/
    it = search_n (myvector.begin(), myvector.end(), 3, 10, mypredicate);

    if (it!=myvector.end())
        cout << "three 10s found at position " << int(it-myvector.begin()) << endl;
    else
        cout << "match not found" << endl;

    //连续的4个大于10的数
    it = search_n (myvector.begin(), myvector.end(), 4, 10, greater<int>());//谓词//其实本函数不规范。
//    it = search_n_if (myvector.begin(), myvector.end(), 4, bind2nd(greater<int>(),10) );//很遗憾,并没有search_n_if
    if (it!=myvector.end())
        cout << "连续的4个大于10的数 " << int(it-myvector.begin()) << endl;
    else
        cout << "match not found" << endl;

    return 0;
}
/******
Output:
    two 30s found at position 2
    three 10s found at position 5
    连续的4个大于10的数 1
******/

 

你可能感兴趣的:(STL,查找算法,search_n,STL_算法)