你好,游客 登录 注册 搜索
背景:
阅读新闻

C++ 关联容器map 类型小结

[日期:2014-07-24] 来源:Linux社区  作者:suool [字体:大 中 小]

二、不修改map对象的查询操作

(1) m.count(k);返回 m 中 k 的出现次数
(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对象

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 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;}

运行结果:

有图可知,用迭代器输出的时候,按照字典序输出。
linux
相关资讯       容器map  关联容器 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款