C++ STL reverse_iterator, a pointer program sample

 

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 type that provides a pointer to an element addressed by a reverse_iterator in C++ programming

To show: How to use the C++ STL reverse_iterator, pointer type that provides a pointer to an element addressed by a reverse_iterator in C++ programming

 

// C++ STL reverse_iterator, pointer

#include <iterator>

#include <algorithm>

#include <vector>

#include <utility>

#include <iostream>

using namespace std;

 

int main(void)

{

// vector container, with typedef to simplify name

typedef vector<pair<int, int> > pVector;

pVector vec;

 

// pushing data, constructing the vector

vec.push_back(pVector::value_type(1, 2));

vec.push_back(pVector::value_type(3, 4));

vec.push_back(pVector::value_type(5, 6));

 

// vector iterator

pVector::iterator pvIter;

// some operations

cout<<"Operation: pvIter->first and pvIter->second"<<endl;

// printing the data

cout<<"The vec vector of integer pairs is:"<<endl;

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

cout<<pvIter->first<<", "<<pvIter->second<<endl;

// another vector iterator

pVector::reverse_iterator rpvIter;

// some operations

cout<<"\nOperation: reverse rpvIter->first and rpvIter->second";

// printing the data

cout<<"\nThe vec vector reversed is:"<<endl;

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

cout<<rpvIter->first<< ", " <<rpvIter->second<<endl;

// more operation

cout<<"\nOperation: pos = vec.begin() then pos++...";

pVector::iterator pos = vec.begin();

pos++;

// printing the result

cout<<"\nThe iterator pos points to: "<<pos->first<< ", " <<pos->second<<endl;

cout<<"\nOperation: reverse, rpos(pos)";

// another operation

pVector::reverse_iterator rpos(pos);

// printing the result

cout<<"\nThe iterator rpos points to: "<<rpos->first<< ", " <<rpos->second<<endl;

return 0;

}

 

Output examples:

 

Operation: pvIter->first and pvIter->second

The vec vector of integer pairs is:

1, 2

3, 4

5, 6

Operation: reverse rpvIter->first and rpvIter->second

The vec vector reversed is:

5, 6

3, 4

1, 2

Operation: pos = vec.begin() then pos++...

The iterator pos points to: 3, 4

Operation: reverse, rpos(pos)

The iterator rpos points to: 1, 2

Press any key to continue . . .

 

 

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