Standard Map 2
#include <iostream> #include <string> #include <map> using namespace std; main() { map<string, int> stoi = { { "help", 1 }, { "ring", 2 }, { "sink", 3 }, { "bye", 4 } }; while(true) { // Red the command in. string in; cout << "> "; cin >> in; if(!cin) break; // Find the command. auto i = stoi.find(in); if(i == stoi.end()) { cout << "Unknown command " << in << endl; continue; } // Process known commands. switch(i->second) { case 1: cout << "Commands are help, ring, sink and bye." << endl; break; case 2: cout << "Brrrriiinnnnng" << endl; break; case 3: cout << "Blub, blub, blub" << endl; break; case 4: exit(0); } } }

This gives the hint of a useful application: convert input strings to integers so they can be fed to a switch. A couple of new things here:

This program shows an alternate way of initializing the map, using a curly-brace list similar to an array. A map is a list of pairs, so the initializer is a list of sublists.

Another new feature used here is the auto type declaration of the iterator i. The type of i here is the same as in the previous example, map<string,int>::iterator, but auto is easier to type. The auto type can be used whenever a variable is given an initial value, and it means that the variable has the same type as that value. It works just fine when the initial value is a int, but is much more useful when it's something complicated.