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有效,否则会出现未定义行为。