C++ STL  iterator, traverse the container using advance() 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, advance()  to increment an iterator by a specified number of positions in C++ programming

To show: How to use the C++ iterator, advance() to increment an iterator by a specified number of positions in C++ programming

 

// C++ STL iterator, advance()

#include <iterator>

#include <list>

#include <iostream>

using namespace std;

 

int main(void)

{

int i;

// list container

list<int> lst;

 

// push/insert data

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

lst.push_back(i);

 

// list iterator

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

 

// print the data

cout<<"The lst list data: ";

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

cout<<*lstIter<<" ";

cout<<endl;

 

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

advance(lstpos, 5);

cout<<"Advanced lstpos 5 steps forward pointing to the "<<*lstpos<<endl;

advance(lstpos, -4);

cout<<"Moved lstpos 4 steps backward pointing to the "<<*lstpos<<endl;

advance(lstpos, 8);

cout<<"Finally, the last element pointed by iterator lstpos is: "<<*lstpos<<endl;

return 0;

}

 

Output examples:

 

The lst list data: 1 2 3 4 5 6 7 8 9 10

The the first element pointed by iterator lstpos is: 1

Advanced lstpos 5 steps forward pointing to the 6

Moved lstpos 4 steps backward pointing to the 2

Finally, the last element pointed by iterator lstpos is: 10

Press any key to continue . . .

 

 

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