C++ STL  iterator, traverse the map 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 map container in C++ programming

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

 

// C++ STL iterator, map simple example

#include <iostream>

#include <map>

#include <string>

using namespace std;

 

int main(void)

{

// type of the collection

map<int, string> mp;

 

// set container for int/string values insert some elements in arbitrary order

// notice a value with key 1

mp.insert(make_pair(5,"learn"));

mp.insert(make_pair(2,"map"));

mp.insert(make_pair(1,"Testing"));

mp.insert(make_pair(7,"tagged"));

mp.insert(make_pair(4,"strings"));

mp.insert(make_pair(6,"iterator!"));

mp.insert(make_pair(1,"the"));

mp.insert(make_pair(3,"tagged"));

 

// iterate over all elements and print, element member second is the value

map<int, string>::iterator pos;

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

cout<<pos->second<<' ';

cout<<endl;

return 0;

}

 

Output examples:

 

Testing map tagged strings learn iterator! tagged

Press any key to continue . . .

 

 

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