背景:在C++ Standard Library中,Map容器使用pair(Key/Value)存儲元素,而且不允許重復元素。如果給定一個Key,存在著唯一的對應的Value,Key與Value存在著某種關聯,由此,可將Map作為關聯數組使用。 現舉例如下 Test OS: Windows 7 Test IDE: Visual Studio 2005 Code Example: [cpp] #include "stdafx.h" #include <iostream> #include <map> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { /* Create map / associative map * - keys are strings * - values are float */ typedef map<string, float> StringFloatMap; // create empty container StringFloatMap stocks; // insert some elements stocks["TXKG"] = 276.50; stocks["GOOG"] = 700.34; stocks["AAPL"] = 498.26; stocks["BMW"] = 823.23; stocks["NONE"] = 0.72; stocks["NOKIA"] = 12.25; // print all elements StringFloatMap::iterator pos; for(pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock:" << pos->first << "\t" << "price:" << pos->second << endl; } cout << endl; // all stocks doubled for(pos = stocks.begin(); pos != stocks.end(); ++pos) { pos->second *= 2; } // print all elements for(pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock:" << pos->first << "\t" << "price:" << pos->second << endl; } cout << endl; // rename key from "AAPL" to "APPLE" stocks["APPLE"] = stocks["AAPL"]; stocks.erase("AAPL"); // print all elements for(pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock:" << pos->first << "\t" << "price:" << pos->second << endl; } cout << endl; system("pause"); return 0; } #include "stdafx.h" #include <iostream> #include <map> #include <string> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { /* Create map / associative map * - keys are strings * - values are float */ typedef map<string, float> StringFloatMap; // create empty container StringFloatMap stocks; // insert some elements stocks["TXKG"] = 276.50; stocks["GOOG"] = 700.34; stocks["AAPL"] = 498.26; stocks["BMW"] = 823.23; stocks["NONE"] = 0.72; stocks["NOKIA"] = 12.25; // print all elements StringFloatMap::iterator pos; for(pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock:" << pos->first << "\t" << "price:" << pos->second << endl; } cout << endl; // all stocks doubled for(pos = stocks.begin(); pos != stocks.end(); ++pos) { pos->second *= 2; } // print all elements for(pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock:" << pos->first << "\t" << "price:" << pos->second << endl; } cout << endl; // rename key from "AAPL" to "APPLE" stocks["APPLE"] = stocks["AAPL"]; stocks.erase("AAPL"); // print all elements for(pos = stocks.begin(); pos != stocks.end(); ++pos) { cout << "stock:" << pos->first << "\t" << "price:" << pos->second << endl; } cout << endl; system("pause"); return 0; } Test Result as follow: 可見,使用pair第一元素類型作為下標,尋址到該Key對應的Value的引用,可以很方便地操縱元素。 這裡需要注意: 當使用Key作為下標時,如果Map中已經存在該元素,則返回該元素Value的引用,如果不存在,則會插入一個以下標為Key的元素,並使用Value對應數據類型的Default構造函數初始化Value。即上例中中如果使用語句stocks["abcd"] = 5.0,則插入Key為“abcd”的元素,並以float 0 初始化,緊接著,將該元素的Value賦值為5.0。