(2) m.find(k); 如果 m 容器中存在按 k 索引的元素,则返回指向该元素的迭代器。如果不存在,则返回超出末端迭代器
-----使用count检查对象总某键是否存在
对于 map 对象,count 成员的返回值只能是 0 或 1。map 容器只允许一个键对应一个实例,所以 count 可有效地表明一个键是否存在。如果返回值非 0,则可以使用下标操作符来获取该键所关联的值,而不必担心这样做会在 map 中插入新元素:
int occurs = 0;
if (word_count.count("foobar"))
occurs = word_count["foobar"];
当然,在执行 count 后再使用下标操作符,实际上是对元素作了两次查找。如果希望当元素存在时就使用它,则应该用 find 操作。
-----读取元素而不插入该元素
find 操作返回指向元素的迭代器,如果元素不存在,则返回 end 迭代器:
如果希望当具有指定键的元素存在时,就获取该元素的引用,否则就不在容器中创建新元素,那么应该使用 find。
删除map元素map同样提供begin和end运算。以生成遍历整个元素的迭代器
ok,that`s all .
实际程序演练一、单词统计
代码一:
// 建立一个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>// 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;}
运行结果:
有图可知,用迭代器输出的时候,按照字典序输出。