STL 알고리즘 노트

find_end

//  2   1         ,        2

template <class ForwardIterator1, class ForwardIterator2>
   ForwardIterator1 find_end ( ForwardIterator1 first1, ForwardIterator1 last1,
                               ForwardIterator2 first2, ForwardIterator2 last2 );

template <class ForwardIterator1, class ForwardIterator2, class BinaryPredicate>
   ForwardIterator1 find_end ( ForwardIterator1 first1, ForwardIterator1 last1,
                               ForwardIterator2 first2, ForwardIterator2 last2,
                               BinaryPredicate pred );

template<class ForwardIterator1, class ForwardIterator2>
  ForwardIterator1 find_end ( ForwardIterator1 first1, ForwardIterator1 last1,
                              ForwardIterator2 first2, ForwardIterator2 last2)
{
  if (first2==last2) return last1;  // specified in C++11

  ForwardIterator1 ret = last1;

  while (first1!=last1)
  {
    ForwardIterator1 it1 = first1;
    ForwardIterator2 it2 = first2;
    while (*it1==*it2) {    // or: while (pred(*it1,*it2)) for the pred version
        ++it1; ++it2;
        if (it2==last2) { ret=first1; break; }
        if (it1==last1) return ret;
    }
    ++first1;
  }
  return ret;
}



//  
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include "boost/array.hpp"
using namespace std;
using namespace boost;
int main()
{
    vector<int> v;
    array<int,3> a = {10,20,40};
    for(int i = 10 ; i < 100 ; i+= 10)
        v.push_back(i);
    for(int i = 10 ; i < 100 ; i+= 10)
        v.push_back(i);
    vector<int>::iterator it = find_end(v.begin(),v.end(),a.begin(),a.end());
    copy(v.begin(),v.end(),ostream_iterator<int>(cout," "));
    cout<<it - v.begin() <<endl;

    return 0;
}
includes
//        ,range1   range2
template <class InputIterator1, class InputIterator2>
  bool includes ( InputIterator1 first1, InputIterator1 last1,
                  InputIterator2 first2, InputIterator2 last2 )
{
  while (first1!=last1)
  {
    if (*first2<*first1) break;
    else if (*first1<*first2) ++first1;
    else { ++first1; ++first2; }
    if (first2==last2) return true;
  }
  return false;
}


   

좋은 웹페이지 즐겨찾기