Why there is no std::copy_if algorithm?

后端 未结 6 1204
无人共我
无人共我 2020-12-03 04:23

Is there any specific reason for not having std::copy_if algorithm in C++ ? I know I can use std::remove_copy_if to achieve the required behavior. I think it is coming in C+

6条回答
  •  北海茫月
    2020-12-03 04:41

    Just for completeness I will add that boost has boost::algorithm::copy_if for those of you who cannot use c++11's version (like me) in boost/algorithm/cxx11/copy_if.hpp which will use std::copy_if when:

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

    Example:

    #include 
    #include  // for 'list_of()'
    #include 
    
    #include 
    #include 
    #include 
    
    struct Odd
    {
      bool operator()(int n)
      {
        return n & 1;
      }
    };
    
    int main()
    {
      std::vector v = boost::assign::list_of(0)(1)(2)(3)(4);
      BOOST_FOREACH(int i, v)
        std::cout << i << ' ' ;
    
      std::vector 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 << ' ' ;
    
    }
    

    Output:

    0 1 2 3 4 
    1 3 
    

提交回复
热议问题