C++ STL algorithm, reverse() code example

Compiler: Visual C++ Express Edition 2005

Compiled on Platform: Windows XP Pro SP2

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() to reverse the order of the elements within a range in C++ programming

To show: How to use the C++ algorithm, reverse() to reverse the order of the elements within a range in C++ programming

" face="Arial"> // C++ STL algorithm, reverse()

#include <vector>

#include <algorithm>

#include <iostream>

using namespace std;

int main(void)

{

// vector container

vector <int> vec1;

// vector iterator

vector <int>::iterator Iter1;

int i;

// push data in range

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

vec1.push_back(i);

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

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

cout<<*Iter1<<" ";

cout<<endl;

// reverse the elements in the vector

reverse(vec1.begin(), vec1.end());

cout<<"\nThe vec1 vector data with values reversed is: ";

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

cout<<*Iter1<<" ";

cout<<endl;

return 0;

}

Output examples:

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

The vec1 vector data with values reversed is: 20 19 18 17 16 15 14 13 12 11

Press any key to continue . . .