copy_backward

Syntax:

    #include <algorithm>
    iterator copy_backward( iterator start, iterator end, iterator dest );

copy_backward() is similar to copy, in that both functions copy elements from start to end to dest. The copy_backward() function, however, starts depositing elements at dest and then works backwards, such that:

   *(dest-1) == *(end-1)
   *(dest-2) == *(end-2)
   *(dest-3) == *(end-3)
   ...
   *(dest-N) == *(end-N)

The following code uses copy_backward() to copy 10 integers into the end of an empty vector:

   vector<int> from_vector;
   for( int i = 0; i < 10; i++ ) {
     from_vector.push_back( i );
   }
 
   vector<int> to_vector(15);
 
   copy_backward( from_vector.begin(), from_vector.end(), to_vector.end() );
 
   cout << "to_vector contains: ";
   for( unsigned int i = 0; i < to_vector.size(); i++ ) {
     cout << to_vector[i] << " ";
   }
   cout << endl;

The above code produces the following output:

   to_vector contains: 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9

Related Topics: copy, copy_n, swap