C++ STL  iterator, operator- minus 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++ iterator, operator- minus to subtracts one iterator from another and returns the difference in C++ programming

To show: How to use the C++ iterator, operator- minus to subtracts one iterator from another and returns the difference in C++ programming

 

// C++ STL iterator, operator-

#include <iterator>

#include <vector>

#include <iostream>

using namespace std;

 

int main(void)

{

int i;

// vector container

vector<int> vec;

// vector iterator

vector<int>::iterator veciter;

 

// push/insert data

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

vec.push_back(i);

 

// print the data

cout<<"The initial vec vector is: ";

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

cout<<*veciter<<" ";

cout<<endl;

 

cout<<"\nOperation: rvecpos1 = vec.rbegin() and rvecpos2 = vec.rbegin()"<<endl;

vector<int>::reverse_iterator rvecpos1 = vec.rbegin(), rvecpos2 = vec.rbegin();

cout<<"The iterators rvecpos1 & rvecpos2 initially point to the first element in the reversed sequence: "<<*rvecpos1<<endl;

cout<<"\nOperation: for(i = 1; i<=5; ++i) and rvecpos2++"<<endl;

for(i = 1; i<=5; ++i)

rvecpos2++;

cout<<"The iterator rvecpos2 now points to the sixth element in the reversed sequence: "<<*rvecpos2<<endl;

cout<<"\nOperation: diff = rvecpos2 - rvecpos1"<<endl;

vector<int>::difference_type diff = rvecpos2 - rvecpos1;

cout<<"The iterators difference: rvecpos2 - rvecpos1= "<<diff<<endl;

return 0;

}

 

Output examples:

 

The initial vec vector is: 10 11 12 13 14 15

Operation: rvecpos1 = vec.rbegin() and rvecpos2 = vec.rbegin()

The iterators rvecpos1 & rvecpos2 initially point to the first element in the reversed sequence: 15

Operation: for(i = 1; i<=5; ++i) and rvecpos2++

The iterator rvecpos2 now points to the sixth element in the reversed sequence: 10

Operation: diff = rvecpos2 - rvecpos1

The iterators difference: rvecpos2 - rvecpos1= 5

Press any key to continue . . .

 

 

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