原文地址:http://blog.csdn.net/qq844352155/article/details/39136169
function template
<algorithm>
std::copy_if
template <class InputIterator, class OutputIterator, class UnaryPredicate> OutputIterator copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred);
Copy certain elements of range
Copies the elements in the range [first,last)
for which pred returns true
to the range beginning at result.
将符合要求的元素(对元素调用pred返回true的元素)复制到目标数组中。
The behavior of this function template is equivalent to:
|
|
Parameters
- first, last
- Input iterators to the initial and final positions in a sequence. The range copied is
[first,last)
, which contains all the elements between first and last, including
the element pointed by first but not the element pointed by last.InputIterator shall point to a type assignable to the elements pointed by OutputIterator.
要复制的序列范围。
- result
- Output iterator to the initial position of the range where the resulting sequence
is stored. The range includes as many elements as[first,last)
.开始覆盖的位置。
- pred
- Unary function that accepts an element in the range as argument, and returns a value convertible to
bool
. The value returned indicates whether the element is to be copied (iftrue
,
it is copied).The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
接受一个参数并且返回一个bool值的一元函数。
The ranges shall not overlap.
Return value
An iterator pointing to the element that follows the last element written in the result sequence.
返回一个指向最后一个覆盖的元素再后面的一个元素的迭代器。
例子:
#include <iostream> #include <algorithm> #include <vector> #include <array> using namespace std; void copyif(){ vector<int> v1{1,5,7,8,9,10,14,15}; vector<int> v2{99,88}; cout<<"at first,v2="; for(int &i:v2) cout<<i<<" "; cout<<endl; v2.resize(10);//resize(10)!! auto it=copy_if(v1.begin(),v1.end(),v2.end()-5,[](int i){ return i%2==0;});//如果是偶数,则返回true cout<<"after copy_if(v1.begin(),v1.end(),v2.end()-5,[](int i){return i%2==0;})"<<endl; cout<<"v2="; for(int &i:v2) cout<<i<<" "; cout<<endl; cout<<"the return it is :*it="<<*it<<endl; }
运行截图:(v2在copy_if之前resize(10))
Example
|
|
Output:
bar contains: 25 15 5 |
Complexity
Linear in the distance between first and last: Applies pred to each element in the
range and performs at most that many assignments.
Data races
The objects in the range [first,last)
are accessed.
The objects in the range between result and the returned value are modified.
Exceptions
Throws if any of pred, the element assignments or the operations on iterators throws.
Note that invalid arguments cause undefined behavior.
——————————————————————————————————————————————————————————————————
//写的错误或者不好的地方请多多指导,可以在下面留言或者点击左上方邮件地址给我发邮件,指出我的错误以及不足,以便我修改,更好的分享给大家,谢谢。
转载请注明出处:http://blog.csdn.net/qq844352155
author:天下无双
Email:[email protected]
2014-9-8
于GDUT
——————————————————————————————————————————————————————————————————