C++ STL  iterator, distance() 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, distance()  to determine the number of increments between the positions addressed by two iterators in C++ programming

To show: How to use the C++ iterator, distance() to determine the number of increments between the positions addressed by two iterators in C++ programming

 

// C++ STL iterator, distance()

#include <iterator>

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

int i;

// list container

list<int> lst;

 

// insert/push data

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

lst.push_back(3*i);

 

// list iterator

list <int>::iterator lstiter, lstpos = lst.begin();

 

// print the data

cout<<"The list lst data: ";

for(lstiter = lst.begin(); lstiter != lst.end(); lstiter++)

cout<<*lstiter<<" ";

cout<<endl;

 

// some operations

cout<<"\nOperation: lstpos = lst.begin()"<<endl;

cout<<"The first element pointed by iterator lstpos: "<<*lstpos<<endl;

cout<<"\nOperation: advance(lstpos, 5)"<<endl;

advance(lstpos, 5);

cout<<"lstpos is advanced 5 steps forward to point to: "<<*lstpos<<endl;

list<int>::difference_type lstdiff;

cout<<"\nOperation: lstdiff = distance(lst.begin(), lstpos)"<<endl;

lstdiff = distance(lst.begin(), lstpos);

cout<<"The distance from lst.begin() to lstpos is: "<<lstdiff<<" elements"<<endl;

return 0;

}

 

Output examples:

 

The list lst data: -3 0 3 6 9 12 15 18 21 24 27

Operation: lstpos = lst.begin()

The first element pointed by iterator lstpos: -3

Operation: advance(lstpos, 5)

lstpos is advanced 5 steps forward to point to: 12

Operation: lstdiff = distance(lst.begin(), lstpos)

The distance from lst.begin() to lstpos is: 5 elements

Press any key to continue . . .

 

 

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