copy_backward


Copy a range of items backward to another area.

Copy the elements from the range [ first ... last ) into a range of the same size ending immediately before result , using operator= to replace the existing elements. Return an iterator of the same type as result , positioned at the start of the newly created sequence. The elements in result will be in the same order as the elements in [ first , last ).

Library

Standards<ToolKit>

Declaration


#include <algorithm>

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

Complexity

Time complexity is linear, as ( last - first ) assignments are performed. Space complexity is constant.

Example <ospace/osstd/examples/copyb0.cpp>
#include <iostream>
#include <algorithm>

int numbers[ 5 ] = { 1, 2, 3, 4, 5 };

void
main()
  {
  int result[ 5 ];

  copy_backward( numbers, numbers + 5, result + 5 );

  int i;
  for ( i = 0; i < 5; ++i )
    cout << numbers[ i ] << ` `;
  cout << "\n";
  for ( i = 0; i < 5; ++i )
    cout << result[ i ] << ` `;
  cout << "\n";
  }

1 2 3 4 5
1 2 3 4 5
Example <ospace/osstd/examples/copyb1.cpp>
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>

void
main()
  {
  vector< int > v1( 10 );
  for ( size_t i = 0; i < v1.size(); ++i )
    v1[ i ] = i;
  vector< int > v2( v1.size() );

  copy_backward( v1.begin(), v1.end(), v2.end() );

  ostream_iterator< int > iter( cout, " " );
  copy( v2.begin(), v2.end(), iter );
  cout << "\n";
  }

0 1 2 3 4 5 6 7 8 9

Copyright©1994-2026 Recursion Software LLC
All Rights Reserved - For use by licensed users only.