#include #include #include using namespace std; //--------------------------- // Utility printing methods //--------------------------- void printSeparator(string s) { cout << endl << "=====================================================" << endl; cout << s << endl; } template void dumpMap(const T c) { for (auto const &el : c) { // the value, el, is a pair (key,mapped value) cout << el.first << " -> " << el.second << endl; } } //--------------------------- // mainline //--------------------------- int main(int argc, char *argv[]) { map orderedMap = { {"one", 1}, {"two", 2}, }; unordered_map unorderedMap = { {"one", 1}, {"two", 2}, }; printSeparator("Ordered map:"); cout << endl << "orderedMap[one] == " << orderedMap["one"] << endl; orderedMap.insert({"three", 3}); orderedMap["four"] = 4; cout << "Ordered map:" << endl; dumpMap(orderedMap); printSeparator("Unordered map:"); cout << endl << "unorderedMap[one] == " << unorderedMap["one"] << endl; unorderedMap.insert({"three", 3}); unorderedMap["four"] = 4; cout << "Unordered map:" << endl; dumpMap(unorderedMap); // Sure, the key can be an int... printSeparator("int key map:"); unordered_map intStringMap = { {1, "one"}, {10, "ten"}, {100, "one hundred"}, {1000, "one thousand"} }; cout << endl << "intStringMap:" << endl; dumpMap(intStringMap); // What happens when this statement is executed? cout << endl << "intStringMap[6] == " << intStringMap[6] << endl; cout << "intStringMap now is:" << endl; dumpMap(intStringMap); try { cout << endl << "intStringMap.at(8) == " << intStringMap.at(8) << endl; } catch (...) { cout << endl << "intStringMap.at(8) == caught exception" << endl; } return 0; }