Effective_STL 学习笔记(三十六) 了解 copy_if 的正确 实现

STL 提供了 11 个名字带有 “copy” 的算法

    copy        copy_backward

    replace_copy     reverse_copy

    replace_copy_if      unique_copy

    remove_copy    rotate_copy

    remove_copy_if   partial_sort_copy

    unintialized_copy

没有一个是 copy_if 的算法。。。

想要实现把一个 vector 中所有的有缺陷的 Widget 写到 cerr(如果存在 copy_if):

1   bool isDefective( const Widget & w );  // 判断 Widget 是否有缺陷
2   vector<Widget> widgets;
3   . . . 
4   copy_if( widgets.begin(), widgets.end(), ostream_iterator<Widget>(cerr, "\n"), isDefective );
5           // 不能编译,因为 STL 中没有 copy_if 算法
扫描二维码关注公众号,回复: 4300994 查看本文章

copy_if 正确的微不足道的实现:

 1   template< typename InputIterator, typename OutputIterator, typename Predicate >
 2   OutputIterator copy_if( InputIterator begin, InputIterator end, 
 3                   OutputIterator destBegin, Predicate p )
 4   {
 5     while( begin != end )
 6     {
 7       if( p(*begin) )
 8         *destBegin++ = *begin;
 9       ++begin;
10     }  
11     return destBegin;
12   }

copy_if 非常重要

猜你喜欢

转载自www.cnblogs.com/kidycharon/p/10042592.html