std::copy, std::copy_if
Defined in header <algorithm>
|
||
template< class InputIterator, class OutputIterator >
OutputIterator copy( InputIterator first, InputIterator last, OutputIterator d_first ); |
(1) | |
template< class InputIterator, class OutputIterator, class UnaryPredicate >
OutputIterator copy_if( InputIterator first, InputIterator last, |
(2) | (since C++11) |
Copies the elements in the range, defined by [first, last), to another range beginning at d_first. The second function only copies the elements for which the predicate pred returns true.
Contents |
[edit] Parameters
first, last | - | the range of elements to copy | |||||||||
d_first | - | the beginning of the destination range. If d_first is within [first, last), std::copy_backward must be used instead of std::copy. | |||||||||
pred | - | unary predicate which returns true for the required elements. The signature of the predicate function should be equivalent to the following:
The signature does not need to have const &, but the function must not modify the objects passed to it. |
[edit] Return value
Output iterator to the element in the destination range, one past the last element copied.
[edit] Complexity
1) Exactly last - first assignments
2) Exactly last - first applications of the predicate
[edit] Possible implementation
First version |
---|
template<class InputIterator, class OutputIterator> OutputIterator copy(InputIterator first, InputIterator last, OutputIterator d_first) { while (first != last) { *d_first++ = *first++; } return d_first; } |
Second version |
template<class InputIterator, class OutputIterator, class UnaryPredicate> OutputIterator copy_if(InputIterator first, InputIterator last, OutputIterator d_first, UnaryPredicate pred) { while (first != last) { if(pred(*first)) *d_first++ = *first; first++; } return d_first; } |
[edit] Example
The following code uses copy to both copy the contents of one vector to another and to display the resulting vector:
#include <algorithm> #include <iostream> #include <vector> #include <iterator> int main() { std::vector<int> from_vector; for (int i = 0; i < 10; i++) { from_vector.push_back(i); } std::vector<int> to_vector(10); std::copy(from_vector.begin(), from_vector.end(), to_vector.begin()); std::cout << "to_vector contains: "; std::copy(to_vector.begin(), to_vector.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << std::endl; }
Output:
to_vector contains: 0 1 2 3 4 5 6 7 8 9
[edit] See also
copies a range of elements in backwards order (function template) |
|
copies a range of elements omitting those that satisfy specific criteria (function template) |