copy_backward algorithm

Copy_backward() STL Algorithm

The copy_backward() algorithm is the same as copy()except that it moves the elements from the end of the sequence first.

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

Copy range of elements backwards
Copies the elements in the range [first,last) into a range whose last element is result. The function begins by copying *(last-1) into *(result-1),
and then follows backwards by the elements preceeding these, until first is reached (and including it).

Returns an iterator to the first element in the destination range.

Assigns the values of elements from a source range to a destination range, iterating through the source sequence
of elements and assigning them new positions in a backward direction.

Implementation of copy_backward() algorithm


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

using namespace std;

typedef int type;

void print_vector(vector <type> vec0)
{
 vector <type>::iterator it;
 for ( it = vec0.begin( ) ; it != vec0.end( ) ; it++ )
 cout << *it << " ";
 cout<< endl;
}

int main( )
{
 vector <type> vec0, vec1;
 vector <type>::iterator it1, its2;

for ( int i = 0 ; i <= 10 ; i++ )
 {
 vec0.push_back(i*10 );
 vec1.push_back(i );
 }

cout<< "print vectors befor copy_backward "<< endl;
 print_vector(vec0);
 print_vector(vec1);

copy_backward( vec0.begin( )+5, vec0.begin( ) + 10, vec1.begin( )+8 );
 cout<< ""<< endl;

cout<< "print vectors after copy_backward "<< endl;
 print_vector(vec0);
 print_vector(vec1);

copy_backward( vec0.begin( ), vec0.begin( ) +5, vec0.end() );
 cout<< ""<< endl;

cout<< "print vector after copy_backward "<< endl;
 print_vector(vec0);
}//end of main

Program Output:

print vectors befor copy_backward
0 10 20 30 40 50 60 70 80 90 100
0 1 2 3 4 5 6 7 8 9 10

print vectors after copy_backward
0 10 20 30 40 50 60 70 80 90 100
0 1 2 50 60 70 80 90 8 9 10

print vector after copy_backward
0 10 20 30 40 50 0 10 20 30 40
Proudly powered by WordPress   Premium Style Theme by www.gopiplus.com
%d bloggers like this: