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.
The behavior of this function template is equivalent to:
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;
}
| |
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 (if true
, it is copied).
The function shall not modify any of its arguments.
This can either be a function pointer or a function object.
The ranges shall not overlap.
Return value
An iterator pointing to the element that follows the last element written in the result sequence.
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
// copy_if example
#include <iostream> // std::cout
#include <algorithm> // std::copy_if, std::distance
#include <vector> // std::vector
int main () {
std::vector<int> foo = {25,15,5,-5,-15};
std::vector<int> bar (foo.size());
// copy only positive numbers:
auto it = std::copy_if (foo.begin(), foo.end(), bar.begin(), [](int i){return !(i<0);} );
bar.resize(std::distance(bar.begin(),it)); // shrink container to new size
std::cout << "bar contains:";
for (int& x: bar) std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
| |
Output:
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.
See also
- copy
- Copy range of elements (function template
)
- replace_copy_if
- Copy range replacing value (function template
)
- remove_copy_if
- Copy range removing values (function template
)