STL Algorithms 之 copy_if

本文探讨了C++中使用模板函数和迭代器进行数据操作的方法,通过实例展示了如何高效地筛选和复制特定条件下的元素。
#include <algorithm>
#include <functional>
#include <vector>
#include <iostream>

using namespace std;

template <class T>
void print(T& c){
   for( typename T::iterator i = c.begin(); i != c.end(); i++ ){
      std::cout << *i << endl;
   }
}


template<class InputIterator, class OutputIterator, class Predicate >
OutputIterator copy_if( InputIterator start, InputIterator stop,OutputIterator out, Predicate select ){
   while( start != stop ){
      if( select( *start ) )
         *out++ = *start;
      ++start;
   }
   return out;
}

int main( )
{
   const int numbers = 7;
   const int num[numbers] = { 5, 0, 3, 2, 1, 4, 7 };
   vector<int> v1( num, num+numbers );
   print( v1 );

   vector<int> v2;
   copy_if( v1.begin(), v1.end(), back_inserter( v2 ),bind2nd( less<int>(), 10 ) );
   print( v2 );
}
  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值