[英]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);
});
编写自己的东西很容易:
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.