Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to use the copy_backward() function in C++

Harsh Jain

What is copy_backward()?

The copy_backward() function is available in the <algorithm.h> header fileThe files that tell the compiler how to call some functionality. in C++. This function is used to copy the elements (within the specified range) to a result vector starting from the end of the result vector.

The order of the elements will not be reversed.


The copy_backward() function accepts the following parameters:

  • first: This is an iterator that points to the array’s first index or vector from where we want to perform the copy operation.

  • last: This is an iterator that points to the last index of the array or vector to where we want to perform the copy operation.

  • result: This is an iterator that points to the end of the new array or vector 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_backward() function returns an iterator that points to the first element in the destination sequence where all the elements have been copied.


Let’s take an example vector containing the elements 10, -20, 30, 40,-50, 60, and 70.

If we apply the copy_backward() function on these elements and copy only the 5 elements, the elements in our result vector, which is the same size as the original vector, will be 0, 0, 10, -20, 30, 40, and -50.

Here, we can see that the elements have been copied in the result vector from the backwards position.


Let’s have a look at the code:

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

using namespace std;

int main() {
  vector<int> num = {10, -20, 30, 40, -50, 60, -70};
  vector<int> vec (7);

  // copy 5 elements and store in result vector from backward direction.
  copy_backward(num.begin(), num.begin() + 5, vec.end());
  // Print the result vector
  cout << "Copied Vector contains: ";
  for (int x: vec)
    cout << x << " ";

  return 0;
Use copy_backward() function in C++


  • From lines 1 to 3, we import the required header files.

  • In line 9, we create an array of integers.

  • In line 10, we create the vector where we want to store the copied data from the array.

  • In line 13, we call the copy_backward() function and pass the required parameters.

We pass the vec.end() as the ending pointer of our result vector.

  • From lines 16 to 21, we print the copied data using a for loop.

Note that, in the end, many zeros are printed. To avoid this, we can resize the result vector after copying the elements to prevent any extra memory usage.

So, in this way, we can use the copy_backward() function to easily copy elements and store them backwards.



View all Courses

Keep Exploring