C++ STL algorithm, reverse_copy() program example

 

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

Header file: Standard

Additional project setting: Set project to be compiled as C++

Project -> your_project_name Properties -> Configuration Properties -> C/C++ -> Advanced -> Compiled As: Compiled as C++ Code (/TP)

Other info: none

To do: Using the C++ reverse_copy() to reverse the order of the elements within a source range while copying them into a destination range in C++ programming

To show: How to use the C++ algorithm, reverse_copy() to reverse the order of the elements within a source range while copying them into a destination range in C++ programming

 

// C++ STL algorithm, reverse_copy()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container

vector <int> vec1, vec2(11);

// vector iterators

vector <int>::iterator Iter1, Iter2;

int i;

 

// push data into vector container

for(i = 10; i <= 20; i++)

vec1.push_back(i);

 

// print the data

cout<<"The original vec1 vector data is: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

// reverse the elements in the vector

reverse_copy(vec1.begin(), vec1.end(), vec2.begin());

cout<<"\nThe copy vec2 vector data of the reversed vec1 vector is: ";

for(Iter2 = vec2.begin(); Iter2 != vec2.end(); Iter2++)

cout<<*Iter2<<" ";

cout<<endl;

cout<<"\nThe original vec1 vector unmodified as: ";

for(Iter1 = vec1.begin(); Iter1 != vec1.end(); Iter1++)

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

 

Output examples:

 

The original vec1 vector data is: 10 11 12 13 14 15 16 17 18 19 20

The copy vec2 vector data of the reversed vec1 vector is: 20 19 18 17 16 15 14 13 12 11 10

The original vec1 vector unmodified as: 10 11 12 13 14 15 16 17 18 19 20

Press any key to continue . . .

 

C and C++ Programming Resources | C & C++ Code Example Index