簡體   English   中英

為什么沒有std :: copy_if算法?

[英]Why there is no std::copy_if algorithm?

在C ++中沒有std :: copy_if算法的具體原因是什么? 我知道我可以使用std :: remove_copy_if來實現所需的行為。 我認為它是在C ++ 0x中出現的,但是一個簡單的copy_if需要一個范圍,一個輸出迭代器和一個仿函數就可以了。 它只是簡單地錯過了還是還有其他原因呢?

根據Stroustrup的“The C ++ Programming Language”,它只是一個過度的觀點。

(作為引用,在提升郵件列表中回答了同樣的問題: copy_if

Stroustrup說他們忘記了。 它是在C ++ 11中。

但是,您可以使用remove_copy_if (實際上應該稱為copy_if_not )以及not1

只是為了完整性,如果有人用谷歌搜索他/她的方式來解決這個問題,應該提到現在(在C ++ 11之后) 一個副本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);
          });

多個 來源 表明它被意外地排除在STL之外。

但是,我不確定這是一個事實還是一個自我延續的神話。 如果有人能指出一個比互聯網隨機帖子的鏈接更可信的來源,我將不勝感激。

編寫自己的東西很容易:

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

為了完整性,我將補充一點,對於那些不能在boost/algorithm/cxx11/copy_if.hpp中使用c ++ 11版本(比如我)的人來說, boost::algorithm::copy_if boost/algorithm/cxx11/copy_if.hpp將使用std::copy_if boost/algorithm/cxx11/copy_if.hpp

#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 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM