36 理解copy_if算法的正确实现

copy_if 在STL中没有实现,复制区间满足某个判别式的所有元素,需要自己来实现。
注:C++11中已经自带copy_if算法
代码如下:
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
using namespace std;

bool isDefective(int num)
{
	return num > 0;
}

namespace NOSTD{

//不完美的实现
template<typename InputIterator,
		 typename OutputIterator, typename Predicate>
OutputIterator copy_if(InputIterator begin,InputIterator end,
						OutputIterator destBegin,Predicate p)
{
	return remove_copy_if(begin,end,destBegin,not1(ptr_fun(p))); 
} 

//正确的实现
template<typename InputIterator,
		 typename OutputIterator, typename Predicate>
OutputIterator copy_if1(InputIterator begin,InputIterator end,
						OutputIterator destBegin,Predicate p)
{
	while (begin != end)
	{  
		if (p(*begin)) 
		  *destBegin++ = *begin;
		++begin;
    }  
  return destBegin;  
}

};


猜你喜欢

转载自blog.csdn.net/weixin_28712713/article/details/80908909
36
今日推荐