Algorithm Copy Backward Function - C++ Programming Tutorial
C++ Course / STL Algorithm / Algorithm Copy Backward Function

Algorithm Copy Backward Function

BLUF: Mastering Algorithm Copy Backward Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Algorithm Copy Backward Function

C++ is renowned for its efficiency. Learn how Algorithm Copy Backward Function enables low-level control and high-performance computing in the tutorial below.

The C++ copy_backward function is employed to duplicate elements in a reversed sequence, taking in three parameters to copy elements within the [first, last] range. The duplication process initiates in reverse sequence with the endpoint set at 'result'.

Syntax

Example

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

Parameter

It serves as a bidirectional iterator pointing to the initial element within the range, with the element itself being encompassed within the range.

The ## Parameter iterator points to the final element in the range, excluding the element itself within the range.

It serves as a bidirectional iterator pointing to the ultimate location of the duplicated elements.

Return value

The function provides an iterator for the initial element in a series of duplicated items.

Example 1

Example

#include <iostream>     
#include <algorithm>    
#include <vector>       
int main () 
{ std::vector<int> newvector;
  for (int k=1; k<=5; k++)
  newvector.push_back(k*5);          
  newvector.resize(newvector.size()+3);  
  std::copy_backward ( newvector.begin(), newvector.begin()+5, newvector.end() );
  std::cout << "newvector contains:";
  for (std::vector<int>::iterator ti=newvector.begin(); ti!=newvector.end(); ++ti)
  std::cout << ' ' << *ti;
  std::cout << '\n';
  return 0;
}

Output:

Output

newvector contains: 5 10 15 5 10 15 20 25

Complexity

The function's complexity increases linearly as it iterates from the initial element to the final one.

Data races

Some or all of the container entities are being retrieved.

Exceptions

The function will raise an exception if any of the container elements raises an exception.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience