您的位置:首页 > Web前端

effective stl 第36条:理解copy_if的正确实现

2016-09-29 18:57 363 查看
STL 中有11个包含了copy的算法:

copy

copy_backward

replace_copy_if

reverse_copy

replace_copy_if

unique_copy

remove_copy

rotate_copy

remove_copy_if

partial_sort_copy

uninitialized_copy

但是copy_if却偏偏不在其中。

下边是正确但是不完美的copy_if的实现方法:

#include<iostream>
#include<algorithm>
#include<functional>

using namespace std;

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(p));
}
int main()
{

return 0;
}


注意:使用not1的原因是STL不允许“复制所有是的判别式为真的元素”,但是他允许“复制所有判别式不为真的元素”。

为了调用上边的copy_if,你传入的不仅是一个函数对象,而且应该是一个可接配的函数对象。虽然这很容易做到,但是要想成为STL算法,他不应该给客户这样的负担。标准的STL从不要求他的含函数子必须可配接,所以copy_if也应该不例外。下边的是完美的copy_if的实现:

#include<iostream>
#include<algorithm>
#include<functional>

using namespace std;

//下边是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;
}
int main()
{

return 0;
}


其实copy_if是很有用的,可以把这个算法加入到STL的库中,然后在适当的地方使用这个算法。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: