Copy a range of elements
This sample is licensed under the CC0 Public Domain Dedication.
Copy elements from a range to another range or container.
We start with a
source range object on line 9 and, for the purposes
of this example, we assume its elements are of type
On lines 11–12, we copy the elements from the
source range into a
target1, simply by passing the begin and end iterators
of the range to the
std::vector<T>’s constructor. We use
to obtain these iterators.
To copy the elements of
source into a range or container which
already has the appropriate number of elements allocated,
target2 on line 5, we use
on lines 14–15. The first two iterator arguments denote the source
range, and the third iterator argument denotes the start of the
target range. For this to work, the elements must already exist in
the target range.
To demonstrate how we can copy into a container that does not
yet contain any elements, we have an empty
target3 on line 6. For the third argument of
std::copy (lines 17–18), we call
to get an iterator that automatically calls
for each element that is copied.