C++ map used as associative array

Description

C++ map used as associative array

#include <iostream>
#include <string>
#include <map>
using namespace std;
int main()/*from   w  w w . j ava  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;
}



PreviousNext

Related