Source of map04.cpp


  1: //map04.cpp

  3: #include <iostream>
  4: #include <map>
  5: #include <string>
  6: using namespace std;

  8: //This is the "value" class for the key/value pairs.
  9: //Note the inline function definitions.
 10: class Greeting
 11: {
 12: public:
 13:     Greeting()         { greeting = "Hi there!"; }
 14:     Greeting(string s) { greeting = s; }
 15:     string getGreeting() const { return greeting; }
 16: private:
 17:     string greeting;
 18: };


 21: int main()
 22: {
 23:     cout << "\nThis program illustrates the \"unusual\" behavior of "
 24:         "m[kVal] when the map m does\nnot contain a key equal to kVal. "
 25:         "If the map does contain a component with key\nvalue kVal, this "
 26:         "expression gives us the value from the corresponding key/value"
 27:         "\npair. If it does not contain this key, then a new component is "
 28:         "inserted into\nthe map. The new component has the given key, "
 29:         "and the corresponding value is\nthe default value of the value "
 30:         "type (VType) of the pairs in the map m.";
 31:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 33:     cout << "\nFirst we create an empty map and put three numbered "
 34:         "greetings into it.";
 35:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 37:     map<int, Greeting> myGreetings;
 38:     myGreetings[1] = Greeting("Hello!");
 39:     myGreetings[2] = Greeting("How's it goin'?");
 40:     myGreetings[3] = Greeting("Hey! Whatcha been up to?");

 42:     cout << "\nNext we display those greetings.";
 43:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 45:     cout << "\nHere is greeting 1: " << myGreetings[1].getGreeting();
 46:     cout << "\nHere is greeting 2: " << myGreetings[2].getGreeting();
 47:     cout << "\nHere is greeting 3: " << myGreetings[3].getGreeting();
 48:     cout << "\nCurrent size of map = " << myGreetings.size();
 49:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 51:     cout << "\nAnd now for the big surprise ...";
 52:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 54:     cout << "\nWait for it ...";
 55:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 57:     cout << "\nEven though we did not enter this greeting ...";
 58:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');

 60:     cout << "\nHere is greeting 4: " << myGreetings[4].getGreeting();
 61:     cout << "\nAnd now ... size of map = " << myGreetings.size();
 62:     cout << "\nPress Enter to continue ... ";  cin.ignore(80, '\n');
 63: }