functional filter()
1 #include "pch.h" 2 #include <iostream> 3 #include <deque> 4 #include <string> 5 #include <list> 6 #include <algorithm> 7 #include <vector> 8 #include <functional> 9 using namespace std; 10 11 template<typename InputIterator, typename OutputIterator,typename ElemType, typename Comp> 12 OutputIterator 13 filter(InputIterator first, InputIterator last,
OutputIterator at, const ElemType &val, Comp pred) 14 { 15 while((first=find_if(first, last, bind2nd(pred, val)))!=last) 16 { 17 cout << "found value:" << *first << endl; 18 *at++ = *first++; 19 } 20 return at; 21 } 22 23 int main() 24 { 25 const int elem_size = 8; 26 int ia[elem_size] = { 12,8,43,0,6,21,3,7 }; 27 vector<int> ivec(ia,ia+elem_size); 28 int ia2[elem_size]; 29 vector<int> ivec2(elem_size); 30 cout << "filtering integer array for values less than 8\n"; 31 filter(ia, ia + elem_size, ia2, elem_size, less<int>()); 32 cout << "filtering integer vector for values greater than 8\n"; 33 filter(ivec.begin(), ivec.end(), ivec2.begin(), elem_size, greater<int>()); 34 return 0; 35 }