templateCopy certain elements of rangeOutputIterator copy_if (InputIterator first, InputIterator last, OutputIterator result, UnaryPredicate pred);
Copies the elements in the range [first,last)
for which pred returns true
to the range beginning at result.
將符合要求的元素(對元素調用pred返回true的元素)復制到目標數組中。
1
2
3
4
5
6
7
8
9
10
11
12
13
template <class InputIterator, class OutputIterator, class UnaryPredicate>
OutputIterator copy_if (InputIterator first, InputIterator last,
OutputIterator result, UnaryPredicate pred)
{
while (first!=last) {
if (pred(*first)) {
*result = *first;
++result;
}
++first;
}
return result;
}
[first,last)
, which contains all the elements between first and last, including the element pointed by first but not the element pointed by last.[first,last)
.bool
. The value returned indicates whether the element is to be copied (if true
, it is copied).返回一個指向最後一個覆蓋的元素再後面的一個元素的迭代器。
例子:
#include#include #include #include using namespace std; void copyif(){ vector v1{1,5,7,8,9,10,14,15}; vector v2{99,88}; cout<運行截圖:(v2在copy_if之前resize(10))