一個簡單的例子理解C++ map, 運用map統計單詞出現的次數
map 對象的元素是鍵值對(key,value),每個key對應一個value, map默認中按key定義的 “ < ” 排序。
key是一個const 對象不可以改變,其類型為map<k,v>::key_type;
value 是一個非const對象,其類型為map<k,v>::mapped_type;
訪問map可以用迭代器訪問也可以用下標訪問:
1、用迭代器訪問:
map<k,v>::iterator iter = m.begin();......
這時候對迭代器解引用會得到map容器中一個map<k,v>::value_type 類型的值,對於map容器來說該值是pair類型,再標准庫中pair在utility 中聲明,pair<first,second> first 為const 對象保存key;second為非const對象,保存value。
在上面的例子中為pair<const string, int>。因此可以使用迭代器來訪問map中的所有值。
2、用下下標訪問
例如在編寫下面程序時:
1 map<string, int> word_count; // empty 2 // insert default initialized element with key "SK"; then assign 1 to its value 3 word_count["SK"] = 1;
該程序會在map中查找"SK"鍵,如果查找到則將"SK" 對應的值賦值為 1。但是word_count 初始為空,並不存在"SK"鍵,因此 word_count["SK"] = 1;將創建一個"SK"鍵,並將其對應的值初始化為1.
利用這個性質我們可以寫一個之前用數組和其他方式實現起來比較麻煩的單詞統計程序:
1 /*==================================================================*\ 2 * 3 * C++ map 運用---統計單詞出現的次數 4 * 5 * 2013/6/7 by 樊列龍 6 * 7 \*==================================================================*/ 8 9 #include <iostream> 10 #include <cstdlib> 11 #include <string> 12 #include <map> 13 14 using namespace std; 15 16 int main() 17 { 18 map<string,int> word_count;// empty 19 20 string word; 21 22 while(cin >> word) 23 { 24 ++word_count[word]; // 用下標訪問 25 } 26 27 map<string, int>::iterator iter; // iter 為pair 類型(value_type) 28 29 for(iter = word_count.begin(); iter != word_count.end(); iter++) 30 { 31 cout << "[" << iter->first << "] = " << iter->second << endl; 32 } 33 34 return EXIT_SUCCESS; 35 }
測試結果:

fan lie long SK love SK a b c a a b ^Z [SK] = 2 [a] = 3 [b] = 2 [c] = 1 [fan] = 1 [lie] = 1 [long] = 1 [love] = 1
我們可以看到用迭代器輸出的結果是按照鍵(這里是string)的 " < " 邏輯(這里是s字典順序)排序的。