Add key value pair to map, and loop through element in map - C++ STL

C++ examples for STL:map

Description

Add key value pair to map, and loop through element in map

Demo Code

#include <iostream> 
#include <map> // map class-template definition 
using namespace std; 

// define short name for map type used in this program 
typedef map< int, double, less< int > > Mid; 

int main() //ww  w  .j  a  v a 2s  . co  m
{ 
   Mid pairs; 
   pairs.insert( Mid::value_type( 15, 2.7 ) ); 
   pairs.insert( Mid::value_type( 30, 111.11 ) ); 
   pairs.insert( Mid::value_type( 5, 1010.1 ) ); 
   pairs.insert( Mid::value_type( 10, 22.22 ) ); 
   pairs.insert( Mid::value_type( 25, 33.333 ) ); 
   pairs.insert( Mid::value_type( 5, 77.54 ) ); // dup ignored 
   pairs.insert( Mid::value_type( 20, 9.345 ) ); 
   pairs.insert( Mid::value_type( 15, 99.3 ) ); // dup ignored 

   cout << "pairs contains:\nKey\tValue\n" ; 

   // use const_iterator to walk through elements of pairs 
   for ( Mid::const_iterator iter = pairs.begin(); iter != pairs.end(); ++iter ) 
       cout << iter->first << '\t' << iter->second << '\n'; 
}

Result


Related Tutorials