算法的目的很简单,找出小于(大于)elem_size的元素并打印.
先贴上代码:
先贴上代码:
#include
<
algorithm
>
//
泛型算法
#include < functional > // function object
#include < vector >
#include < iostream >
using namespace std;
template < typename InputIterator,typename OutputIterator,
typename ElemType, typename Comp >
OutputIterator
filter(InputIterator first,InputIterator last,
OutputIterator at, const ElemType & val,Comp pred)
{
// 从first到last的地址搜索小于(或大于)val对象的对象,找到后把该对象地址赋给first
while ((first = find_if(first,last,bind2nd(pred,val))) != last)
{
cout << " found value : " << * first << endl;
* at ++=* first ++ ;
}
return at;
}
int main()
{
const int elem_size = 8 ;
//数组测试
int ia[elem_size] = { 12 , 8 , 43 , 0 , 6 , 21 , 3 , 7 };
#include < functional > // function object
#include < vector >
#include < iostream >
using namespace std;
template < typename InputIterator,typename OutputIterator,
typename ElemType, typename Comp >
OutputIterator
filter(InputIterator first,InputIterator last,
OutputIterator at, const ElemType & val,Comp pred)
{
// 从first到last的地址搜索小于(或大于)val对象的对象,找到后把该对象地址赋给first
while ((first = find_if(first,last,bind2nd(pred,val))) != last)
{
cout << " found value : " << * first << endl;
* at ++=* first ++ ;
}
return at;
}
int main()
{
const int elem_size = 8 ;
//数组测试
int ia[elem_size] = { 12 , 8 , 43 , 0 , 6 , 21 , 3 , 7 };
int ia2[elem_size];
//vector测试
vector < int > ivec(ia,ia + elem_size);
vector < int > ivec2(elem_size);
cout << " less than 8 " ;
filter(ia,ia + elem_size,ia2,elem_size,less < int > ());
cout << " greater than 8 " ;
filter(ivec.begin(),ivec.end(),ivec2.begin(),elem_size,greater < int > ());
return 0 ;
}
//vector测试
vector < int > ivec(ia,ia + elem_size);
vector < int > ivec2(elem_size);
cout << " less than 8 " ;
filter(ia,ia + elem_size,ia2,elem_size,less < int > ());
cout << " greater than 8 " ;
filter(ivec.begin(),ivec.end(),ivec2.begin(),elem_size,greater < int > ());
return 0 ;
}
几点说明:
1.函数与元素型别无关,与比较操作无关,更和容器型别无关,这样,函数就初步转化为一个泛型算法了.
2.function object adapter 会对 function object 进行修改操作.上例中bind2nd会将指定值绑定至第二操作数,即val成为pred function object的第二个参数,同理bind1st将指定值绑定至第一操作数.
3.上例中的OutputIterator filter 函数中的OutputIterator对应参数并没有使用引用,因为cout操作是在此函数内进行,所以不需要使用对象的引用.