二、不修改map对象的查询操作
int occurs = 0;
if (word_count.count("foobar"))
occurs = word_count["foobar"];
如果希望当具有指定键的元素存在时,就获取该元素的引用,否则就不在容器中创建新元素,那么应该使用 find。
删除map元素

遍历map对象
实际程序演练
// 建立一个map对象,保存所读入的单词及其出现的次数(以单词为键,对应的值为单词出现的次数)
// 利用下标添加元素
#include <iostream>
#include <map>
#include <string>
using namespace std;
// 2013.11.18 Written by C_SuooL_Hu
int main()
{
// freopen("in.txt","r",stdin);
// freopen("out.txt","w",stdout);
map<string, int> wordCount;
typedef map<string, int> ::iterator valType;
string word;
// 读入单词并统计次数
cout << "Enter some words (Ctrl + Z to end):" << endl;
while (cin >> word)
{
// 如果读入的word存在在容器中,则使键值为word的值++,否则添加以此元素为索引的键,然后键值初始化为0,后++,即为1.
++wordCount[word];
}
// 输出结果,用迭代器
cout << "word\t\t" << "times" << endl;
for (valType iter = wordCount.begin(); iter != wordCount.end(); ++iter)
{
cout << (*iter).first << "\t\t" << (*iter).second << endl;
}
return 0;
}
代码二:
#include <iostream>
#include <map>
#include <string>
using namespace std;
</span><pre style="line-height: 24.5px;" class="cpp" name="code">// 2013.11.18 Written by C_SuooL_Hu</pre>// mapint main() { freopen("in.txt","r",stdin); freopen("out.txt","w",stdout); // count number of times each word occurs in the input map<string, int> word_count;
// empty map from string to int typedef map<string, int> ::iterator valType; string word; while (cin >> word) { // inserts element with key equal to word and value 1; // if word already in word_count, insert does nothing pair<map<string, int>::iterator, bool>
ret =word_count.insert(make_pair(word, 1)); if (!ret.second) // word already in word_count ++ret.first->second; // increment counter }// outputcout << "word\t\t" << "times" << endl;for (valType iter = word_count.begin(); iter != word_count.end(); ++iter){cout
<< (*iter).first << "\t\t" << (*iter).second << endl;}return 0;}

