代码之家  ›  专栏  ›  技术社区  ›  Naveen

为什么没有std::copy\u if算法?

  •  63
  • Naveen  · 技术社区  · 17 年前

    有没有特殊的原因,没有STD::CopyIOF IF算法在C++中?我知道我可以使用std::remove\u copy\u来实现所需的行为。我认为它是在C++0x中出现的,但是一个简单的副本(如果它具有一个范围)、一个输出迭代器和一个函子就很好了。它只是被遗漏了还是有其他原因?

    6 回复  |  直到 17 年前
        1
  •  41
  •   sbk    17 年前

    根据Stroustrup的“C++编程语言”,这只是一种过眼烟云。

    (作为引文,boost邮件列表中回答了相同的问题: copy_if )

        2
  •  27
  •   rlbond    11 年前

    斯特劳斯特鲁普说他们忘了。它是用C++11编写的。

    remove_copy_if (这真的应该称之为 copy_if_not )连同 not1 相反

        3
  •  9
  •   Nikos Athanasiou    12 年前

    有 copy if 算法。它的行为符合预期(将某个谓词返回true的范围内的元素复制到另一个范围)。

    一个典型的用例是

    std::vector<int> foo{ 25, 15, 5, -5, -15 };
    std::vector<int> bar;
    
    // copy only positive numbers:
    auto it = std::copy_if (foo.begin(), foo.end(), std::back_inserter(bar), 
                [](int i){return !(i<0);
              });
    
        4
  •  7
  •   Community Mohan Dere    9 年前

    Multiple sources indicate 它被意外地从STL中漏掉了。

        5
  •  7
  •   alex tingle    15 年前

    写自己的东西非常容易:

    template <class InputIterator, class OutputIterator, class Predicate>
    OutputIterator copy_if(InputIterator first, InputIterator last,
                           OutputIterator result, Predicate pred)
    {
      return std::remove_copy_if(first,last,result,std::not1(pred));
    }
    

    编辑: 此版本适用于所有谓词:

    template <class InputIterator, class OutputIterator, class Predicate>
    OutputIterator copy_if(InputIterator first, InputIterator last,
                           OutputIterator result, Predicate pred)
    {
      while(first!=last)
      {
        if(pred(*first))
            *result++ = *first;
        ++first;
      }
      return result;
    }
    
        6
  •  1
  •   Patryk    10 年前

    为了完整起见,我要补充一点,那就是提高了 boost::algorithm::copy_if 对于那些不能在中使用c++11版本(如我)的人 boost/algorithm/cxx11/copy_if.hpp 哪个会用 std::copy_if

    #if __cplusplus >= 201103L
    //  Use the C++11 versions of copy_if if it is available
    using std::copy_if;         // Section 25.3.1
    #else
    

    例子:

    #include <boost/algorithm/cxx11/copy_if.hpp>
    #include <boost/assign/list_of.hpp> // for 'list_of()'
    #include <boost/foreach.hpp>
    
    #include <iostream>
    #include <vector>
    #include <iterator>
    
    struct Odd
    {
      bool operator()(int n)
      {
        return n & 1;
      }
    };
    
    int main()
    {
      std::vector<int> v = boost::assign::list_of(0)(1)(2)(3)(4);
      BOOST_FOREACH(int i, v)
        std::cout << i << ' ' ;
    
      std::vector<int> out;
      boost::algorithm::copy_if(v.begin(), v.end(), std::back_inserter(out), Odd());
    
      std::cout << std::endl;
    
      BOOST_FOREACH(int i, out)
        std::cout << i << ' ' ;
    
    }
    

    0 1 2 3 4 
    1 3