36. 理解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
  • unitialized_copy

但是STL中却不包括copy_if的实现,如果需要它,必须自己实现。
下面是copy_if的正确实现:

template<typename InputIterator, typename OutputIterator, typename Predicate>
OutputIterator copy_if(InputIterator begin, InputIterator end, OutputIterator destBegin, Predicate p)
{
	while (begin != end)
	{
		if (p(*begin)) *destBegin++ == *begin;
		++begin;
	}
	
	return destBegin;
}

下面是SGI STL中copy算法的实现:

template <class _InputIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_InputIter __first, _InputIter __last, _OutputIter __result, input_iterator_tag, _Distance*)
{
	for (; __first != __last; ++__result, ++__first)
		*__result = *__first;

	return __result;
}

template <class _RandomAccessIter, class _OutputIter, class _Distance>
inline _OutputIter __copy(_RandomAccessIter __first, _RandomAccessIter __last, _OutputIter __result, random_access_iterator_tag, _Distance*)
{
	for (_Distance __n = __last - __first; __n > 0; --__n) 
	{
		*__result = *__first;
		++__first;
		++__result;
	}

	return __result;
}

注意,copy、copy_if算法中都没有对__result进行有效性判断(也不法进行判断), 所以调用方必须确保目标位置__result有效,否则会出现未定义行为。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值