把Map用作关联式数组
MapAdvanceTest.cpp
#include <map> #include <string> #include <iostream> #include <iomanip> #include "MapAdvanceTest.h" #include "../../Core/ContainerUtil.h" using namespace std; void MapAdvanceTest::useAsAssociativeArray() { // create map / associative array // - keys are strings // - values are floats typedef map<string, float> StringFloatMap; StringFloatMap stocks; // create empty container // insert some elements stocks["BASF"] = 369.50; stocks["VW"] = 413.50; stocks["Daimler"] = 819.00; stocks["BMW"] = 834.00; stocks["Siemens"] = 842.20; // print all elements ContainerUtil<StringFloatMap>::printMapInDiv(stocks, "Stock", "Price", 15); // boom (all prices doubled) StringFloatMap::iterator pos; for (pos = stocks.begin(); pos != stocks.end(); ++pos) { pos->second *= 2; } // print all elements ContainerUtil<StringFloatMap>::printMapInDiv(stocks, "Stock", "Price", 15); // rename key from "VW" to "Volkswagen" // - provided only by exchanging element stocks["Volkswagen"] = stocks["VW"]; stocks.erase("VW"); // print all elements ContainerUtil<StringFloatMap>::printMapInDiv(stocks, "Stock", "Price", 15); } void MapAdvanceTest::run() { printStart("useAsAssociativeArray()"); useAsAssociativeArray(); printEnd("useAsAssociativeArray()"); }
运行结果:
---------------- useAsAssociativeArray(): Run Start ----------------
Stock: BASF Price: 369.5
Stock: BMW Price: 834
Stock: Daimler Price: 819
Stock: Siemens Price: 842.2
Stock: VW Price: 413.5
Stock: BASF Price: 739
Stock: BMW Price: 1668
Stock: Daimler Price: 1638
Stock: Siemens Price: 1684.4
Stock: VW Price: 827
Stock: BASF Price: 739
Stock: BMW Price: 1668
Stock: Daimler Price: 1638
Stock: Siemens Price: 1684.4
Stock: Volkswagen Price: 827
---------------- useAsAssociativeArray(): Run End ----------------