# C++ <algorithm> - copy_backward() Function

The C++ algorithm::copy_backward function is used to copy all elements in the range [first, last) to the range terminating at result.

Please note that this function does not reverse the order of copied elements. To reverse the order of elements, algorithm::reverse_copy is used.

### Syntax

```template <class BidirectionalIterator1, class BidirectionalIterator2>
BidirectionalIterator2 copy_backward (BidirectionalIterator1 first,
BidirectionalIterator1 last,
BidirectionalIterator2 result);
```

### Parameters

 `first` Specify initial position of the bidirectional iterator1. The range used is [first,last). `last` Specify final position of the bidirectional iterator1. The range used is [first,last). `result` Specify past-the-end position of the bidirectional iterator2 where the result to be stored.

### Return Value

Returns an iterator pointing to the first element copied to the destination sequence.

### Time Complexity

Linear i.e, Θ(n).

### Example:

In the example below, the algorithm::copy_backward function is used to copy all elements of an array to a vector, terminating at end of the vector.

```#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main (){
int arr[] = {10, 20, 30};
vector<int> vec = {1, 1, 1, 1, 1};
vector<int>::iterator it;

//copy all elements from array to vector
copy_backward(arr, arr+3, vec.end());

cout<<"arr contains:";
for(int i = 0; i < 3; ++i)
cout<<" "<<arr[i];

cout<<"\nvec contains:";
for(it = vec.begin(); it != vec.end(); ++it)
cout<<" "<<*it;

return 0;
}
```

The output of the above code will be:

```arr contains: 10 20 30
vec contains: 1 1 10 20 30
```

❮ C++ <algorithm> Library

5