C++ STL reverse_iterator::operator[ ] 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, operator[ ] to return a reference to an element offset from the element addressed by a reverse_iterator by a specified number of positions in C++ programming
To show: How to use the C++ reverse_iterator, operator[ ] to return a reference to an element offset from the element addressed by a reverse_iterator by a specified number of positions in C++ programming
// C++ STL reverse_iterator, operator[ ]
#include <iterator>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int main(void)
{
int i;
// vector container
vector<int> vec;
// push data in range, constructing the vector
for(i = 10; i<=17; ++i)
vec.push_back(i);
// vector iterators
vector <int>::iterator vIter;
cout<<"Normal...."<<endl;
cout<<"The vec vector data: ";
for(vIter = vec.begin(); vIter != vec.end(); vIter++)
cout<<*vIter<<" ";
cout<<endl;
vector <int>::reverse_iterator rvIter;
cout<<"\nReverse...."<<endl;
cout<<"The vec vector reversed data: ";
for(rvIter = vec.rbegin(); rvIter != vec.rend(); rvIter++)
cout<<*rvIter<<" ";
cout<<endl;
vector <int>::iterator pos;
cout<<"\nFinding data, 15...."<<endl;
cout<<"Operation: pos = find(vec.begin(), vec.end(), 15)"<<endl;
pos = find(vec.begin(), vec.end(), 15);
cout<<"The iterator pos points to: "<<*pos<<endl;
// vector reverse iterators
reverse_iterator<vector<int>::iterator> rpos(pos);
// declare a difference type for a parameter
reverse_iterator<vector<int>::iterator>::difference_type diff = 3;
cout<<"\nOperation: rpos(pos)"<<endl;
cout<<"The iterator rpos points to: "<<*rpos<<endl;
// declare a reference return type & use operator[ ]
reverse_iterator<vector<int>::iterator>::reference refrpos = rpos[diff];
cout<<"\nOperation: refrpos = rpos[diff], where diff = 3"<<endl;
cout<<"The iterator rpos now points to: "<<refrpos<<endl;
return 0;
}
Output examples:
Normal....
The vec vector data: 10 11 12 13 14 15 16 17
Reverse....
The vec vector reversed data: 17 16 15 14 13 12 11 10
Finding data, 15....
Operation: pos = find(vec.begin(), vec.end(), 15)
The iterator pos points to: 15
Operation: rpos(pos)
The iterator rpos points to: 14
Operation: refrpos = rpos[diff], where diff = 3
The iterator rpos now points to: 11
Press any key to continue . . .