C++ STL reverse_iterator::base() 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_iterator::base() to recover the underlying iterator from its reverse_iterator in C++ programming

To show: How to use the C++ reverse_iterator, base() to recover the underlying iterator from its reverse_iterator in C++ programming

 

// C++ STL reverse_iterator, base()

#include <iterator>

#include <algorithm>

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

int i;

// vector container

vector<int> vec;

// vector iterator

vector <int>::iterator vIter, pos, bpos;

// vector reverse iterator

vector<int>::reverse_iterator rvIter;

// integer type reverse iterator

typedef reverse_iterator<vector<int>::iterator>::iterator_type it_vec_int_type;

 

// constructing the vector

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

vec.push_back(i);

 

// print the data

cout<<"The vec vector data: ";

for(vIter = vec.begin(); vIter != vec.end(); vIter++)

cout<<*vIter<<" ";

cout<<endl;

 

// print the data

cout<<"The vec vector reversed data: ";

for(rvIter = vec.rbegin(); rvIter != vec.rend(); rvIter++)

cout<<*rvIter<<" ";

cout<<endl;

 

// do the find() operation

cout<<"\nFinding data...";

cout<<"\nOperation: pos = find(vec.begin(), vec.end(), 13)"<<endl;

pos = find(vec.begin(), vec.end(), 13);

 

// print the result

cout<<"The iterator pos points to: "<<*pos<<endl;

 

// finding the position using reverse iterator

cout<<"\nFinding data, reverse..."<<endl;

cout<<"Operation: rpos(pos)"<<endl;

reverse_iterator<it_vec_int_type> rpos(pos);

cout<<"The reverse_iterator rpos points to: "<<*rpos<<endl;

bpos = rpos.base();

cout<<"The iterator underlying rpos is bpos & it points to: "<<*bpos<<endl;

return 0;

}

 

Output examples:

 

The vec vector data: 10 11 12 13 14 15

The vec vector reversed data: 15 14 13 12 11 10

Finding data...

Operation: pos = find(vec.begin(), vec.end(), 13)

The iterator pos points to: 13

Finding data, reverse...

Operation: rpos(pos)

The reverse_iterator rpos points to: 12

The iterator underlying rpos is bpos & it points to: 13

Press any key to continue . . .

 

 

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