C++ STL reverse iterator using rbegin() and rend() 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++ STL reverse iterators: begin() and rend() in C++ programming

To show: How to use the C++ reverse iterator using rbegin() and rend() in C++ programming

 

// C++ STL reverse iterator using rbegin(), rend() and copy()

#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

 

int main(void)

{

// vector container

vector<int> vec;

 

// insert elements from 1 to 10, constructing vector

for(int i=1; i<=10; ++i)

vec.push_back(i);

 

// print the result

cout<<"vec vector in original order: ";

copy(vec.begin(), vec.end(), ostream_iterator<int> (cout," "));

cout<<endl;

 

// print all element in reverse order

cout<<"vec vector in reverse order: ";

copy(vec.rbegin(), vec.rend(), ostream_iterator<int> (cout," "));

cout<<endl;

return 0;

}

 

Output examples:

 

vec vector in original order: 1 2 3 4 5 6 7 8 9 10

vec vector in reverse order: 10 9 8 7 6 5 4 3 2 1

Press any key to continue . . .

 

 

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