The copy()
function in C++ is used to copy the values from an array/vector within a specified range to another array/vector. This function is available in the <algorithm.h>
header file.
The copy()
function accepts the following parameters:
first
: This is an iterator that points to the first index of the array or vector from where we want to copy the elements.
last
: This is an iterator that points to the last index of the array or vector to where we want to copy the elements.
result
: This is an iterator that points to the new array or vector to where we want to store the copied elements. The size of the result
should be large enough to accommodate the elements in the range [first, last).
The copy()
function returns an iterator that points to the end of the result
where last the element has been copied.
Let’s look at the code now to understand it better.
#include <iostream>#include <vector>#include <algorithm>using namespace std;int main() {int arr[] = {10,20,30,40,50,60,70};vector<int> vec (7);copy(arr, arr + 7, vec.begin());cout << "Copied Vector contains: ";for (int x: vec)cout << x << " ";return 0;}
From lines 1 to 3, we import the required header files.
In line 7, we create an array of integers.
In line 8, we create the vector where we want to store the copied data from the array.
In line 10, we call the copy()
function and pass the required parameters. Note that we pass the vec.begin()
as the starting address of our
From lines 12 to 14, we print the copied data using a for
loop.