C++ STL  iterator, traverse the set container with begin() and end() 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 begin() and end() iterator to traverse the set container in C++ programming

To show: How to traverse the set container in C++ programming using the begin() and end() iterator

 

// C++ STL iterator, set example

#include <iostream>

#include <set>

using namespace std;

 

int main(void)

{

// set container of int data type

set<int> tst;

 

// insert elements

tst.insert(12);

tst.insert(21);

tst.insert(32);

tst.insert(31);

tst.insert(9);

tst.insert(14);

tst.insert(21);

tst.insert(31);

tst.insert(7);

 

// iterate over all elements and print, separated by a space

set<int>::const_iterator pos;

cout<<"set: ";

// pre-increment and pre-decrement are faster than post-increment and post-decrement...

for(pos = tst.begin(); pos != tst.end(); ++pos)

cout<<*pos<<' ';

cout<<endl;

return 0;

}

 

Output examples:

 

set: 7 9 12 14 21 31 32

Press any key to continue . . .

 

 

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