Skip to main content

mapdemo.cpp


// Simple demo of creating and using a map
// (NDE, 2014-01-05)
#include <map>
#include <iostream>
using namespace std;
int main()
{
  // Create a map of strings onto strings
  map<string,string> phonebook;
  // Add a key-value pair to map
  phonebook["Nick"] = "01234 567890";
  // Check whether keys "Nick" and "Joe" are present
  bool nick_is_key = (phonebook.find("Nick") != phonebook.end());
  bool joe_is_key = (phonebook.find("Joe") != phonebook.end());
  cout << "Nick is key? " << boolalpha << nick_is_key << endl;
  cout << "Joe is key?  " << joe_is_key << endl;
  // Use [] to look up values associated with keys "Nick" and "Joe"
  cout << "Value for Nick = " << phonebook["Nick"] << endl;
  cout << "Value for Joe  = " << phonebook["Joe"] << endl;
  // Check again whether keys "Nick" and "Joe" are present
  nick_is_key = (phonebook.find("Nick") != phonebook.end());
  joe_is_key = (phonebook.find("Joe") != phonebook.end());
  cout << "Nick is key? " << nick_is_key << endl;
  cout << "Joe is key?  " << joe_is_key << endl;
  return 0;
}