[5 算法] 36. 理解copy_if算法的正确实现

STL中有11个包含"copy"的算法:

copy copy_backward repalce_copy reverse_copy replace_copy_if ...

但是copy_if算法并没有。

假如有一个函数来判断一个Widget是否有破损:

bool isDefective(const Widget& w);

你打算把一个vector中的所有破损Widget对象写到cerr中。

下面是大多数人以为正确的copy_if实现和调用:

templace<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));
}

copy_if(widgets.begin(), widgets.end(),
        ostream_iterator<Widget>(cerr, "\n"),
        isDefective);

把not1应用到isDefective时会编译出错,第41条会解释为什么not1不能被直接应用到一个函数指针上。

下面是copy_if的正确实现:

templace<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;
}

猜你喜欢

转载自blog.csdn.net/u012906122/article/details/119739913
今日推荐