(1) there are various kinds of iterators: forward, random, input, output,bi-directional, iterator_traits::iterator_category (2) for(; ...) will avoid post increment iterator, since some does not support iter++ (3) C++ func are struct with operator() overridden or std::function as a function_ptr (4) iterator can be de-referenced or indexed in *, [] #include "stdafx.h" #include <iostream> #include <string> #include <vector> #include <functional> #include <algorithm> using namespace std; template<typename ForwardIter, typename Func> void adjacent_pair(ForwardIter first, ForwardIter last, Func func) { if (first != last) { ForwardIter trailer = first; ++first; for (; first != last; ++first, ++trailer) func(*trailer, *first); } }; template<typename SourceIter, typename TargetIter, typename Predicate> std::pair<SourceIter, TargetIter> copy_while(SourceIter srcFirst, SourceIter srcLast, TargetIter tgt, Predicate p) { for (; srcFirst != srcLast && p(*srcFirst); ++srcFirst,++tgt ) *tgt = *srcFirst; return std::make_pair(srcFirst,tgt); }; struct func_cout { inline void operator() (int a, int b) const { cout << a << " " << b << endl; } }; struct func_predicate_even { inline bool operator() (int a) const { return a % 2==0; } } inline void print(int a,int b) { cout << a << "|" << b << endl;} int main() { vector<int> v = { 2,16,36,109,8,999,90,5 }; func_cout a_func; adjacent_pair<vector<int>::iterator, func_cout>(v.begin(), v.end(),a_func); std::function<void(int,int)> f_ptr = print; adjacent_pair<vector<int>::iterator, std::function<void(int, int)>>(v.begin(), v.end(), f_ptr); vector<int> w(5); func_predicate_even pred; auto ret_iter = copy_while(v.begin(),v.end(), w.begin(),pred); cout << *ret_iter.first <<"**"<< *ret_iter.second <<"copied "<<w[1]<< endl; std::string s; getline(cin, s); return 0; }
Saturday, October 29, 2016
C++ iterator, Func as operator () or std:function and predicate as func
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment