Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C++

std::copy: copying a range into existing storage

std::copy assigns every element of an input range to consecutive destination positions and returns the iterator past the last write.

Version: C++23

Syntax

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

std::copy(first, last, result) from <algorithm> proceeds in order and performs exactly N assignments *out = *in, where N is the number of elements in [first, last). It returns the iterator advanced N positions from result; this describes the result and does not require operator +. Order is preserved. Ordinary copying between disjoint objects leaves the source unchanged, but an overlapping left shift can overwrite part of the shared buffer, and a std::move_iterator can move from the source.

The destination must hold all N elements; std::copy does not grow a container unless an insertion iterator is supplied. For the ordinary overload, result must not lie in [first, last). Use std::copy_backward when shifting elements right within one buffer.

The execution-policy overload requires source and destination ranges not to overlap at all. An assignment exception under any standard execution policy, including seq, calls std::terminate. An empty range performs no assignments and returns the unchanged result.

Examples

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

int main() {
    const std::vector<int> source{1, 2, 3};
    std::vector<int> destination(5, -1);
    const auto end = std::copy(source.begin(), source.end(), destination.begin() + 1);
    std::cout << std::distance(destination.begin(), end) << ' ';
    for (std::size_t i = 0; i < destination.size(); ++i) {
        if (i != 0) std::cout << ',';
        std::cout << destination[i];
    }
    std::cout << '\n';
}

Result

4 -1,1,2,3,-1

std::copy → 4 -1,1,2,3,-1

Sources