C++ algorithm copy() function
Example
Copy the contents of a vector into another vector:
vector<int> numbers = {1, 7, 3, 5, 9, 2};
vector<int> copiedNumbers(6);
copy(numbers.begin(), numbers.end(), copiedNumbers.begin());
for (int number : copiedNumbers) {
cout << number << " ";
}
Try it Yourself »
Definition and Usage
The copy()
function copies a the contents of a data range into another data range.
The data ranges are specified by iterators.
Syntax
copy( iterator start, iterator end, iterator destination );
Parameter Values
Parameter | Description |
---|---|
start | Required. An iterator pointing to the start of the data range being copied. |
end | Required. An iterator pointing to the end of the data range being copied. Elements up to this position will be copied, but the element at this position will not be included. |
destination | Required. An iterator pointing to the location that the data will be copied to. |
Technical Details
Returns: | An iterator pointing to the end of the destination data range. |
---|
More Examples
Example
Copy the first three values of a vector into the same vector:
vector<int> numbers = {1, 7, 3, 5, 9, 2};
copy(numbers.begin(), numbers.begin() + 3, numbers.begin() + 3);
for (int number : numbers) {
cout << number << " ";
}
Try it Yourself »
Related Pages
Read more about data structures in our Data Structures Tutorial.
Read more about iterators in our Iterators Tutorial.
Read more about algorithms in our Algorithms Tutorial.