Demonstrate map used as associative array - C++ STL

C++ examples for STL:map

Description

Demonstrate map used as associative array

Demo Code

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()//from  ww w. ja v  a 2  s .  c  o m
{
   string name;
   int pop;
   string states[] = { "A", "B", "C","D", "E", "F"};
   int pops[] = { 4, 2, 8, 7, 1, 9 };
   map<string, int, less<string> > mapStates;       //map
   map<string, int, less<string> >::iterator iter;  //iterator
   for(int j=0; j<6; j++)
   {
      name = states[j];                 //get data from arrays
      pop = pops[j];
      mapStates[name] = pop;            //put it in map
   }
   cout << "Enter state: ";             //get state from user
   cin >> name;
   pop = mapStates[name];               //find population
   cout << "Population: " << pop << ",000\n";
   cout << endl;                        //display entire map
   for(iter = mapStates.begin(); iter != mapStates.end(); iter++)
      cout << (*iter).first << ' ' << (*iter).second << ",000\n";
   return 0;
}

Result


Related Tutorials