std::copy

From Cppreference

Jump to: navigation, search
Defined in header <algorithm>

template< class InputIterator, class OutputIterator >
OutputIterator copy( InputIterator first, InputIterator last, OutputIterator d_first );

Copies the elements in the range, defined by [first, last), to another range beginning at d_first.

Contents

Parameters

first, last - the range of elements to copy
d_first - the beginning of the destination range

Return value

output iterator to the element past the last element copied.

Complexity

linear in the distance between first and last

Equivalent function

template<class InputIterator, class OutputIterator>
OutputIterator copy(InputIterator first, InputIterator last, OutputIterator d_first)
{
    while (first != last) {
        *d_first++ = *first++;
    }
    return d_first;
}

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>
 
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());
 
    cout << "to_vector contains: ";
    std::copy(to_vector.begin(), to_vector.end(), std::ostream_iterator<int>(std::cout, " "));
 
    return 0;
}

Output:

​to_vector contains: 0 1 2 3 4 5 6 7 8 9​

See also

copy_backward
copies a range of elements in backwards order
(function template)
remove_copy
remove_copy_if
copies a range of elements omitting those that satisfy specific criteria
(function template)
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox
In other languages