C++ Primer笔记 map

来源:互联网 发布:java数据库编程 编辑:程序博客网 时间:2024/06/07 06:51

p360

map

map对象的元素是键--值

map迭代器解引用将产生pair类型的对象,在这个pair对象中,它的first元素具有const map<K, V>::key_type类型

而second元素则为map<K, V>::mapped_type类型

eg.

map<string, int> word_count;

map<string, int>::const_iterator iter = word_count.begin();

iter->first = "hello";

iter->second = 2;

或者

(*iter).first = "hello";

(*iter).second = 2;


NOTE:

对于键类型,唯一的约束就是必须支持 ‘<’ 操作符,至于是否支持其他的关系或相等运算则不作要求。

这里的键类型,也就是map容器对象的下标类型,所以list不可以做键类型。


例如:对于以int类型对象为索引关联vector<int>类型对象的map容器,它的mapped_type, key_type, value_type分别是什么?

:它的value_type为pair< const int, vector<int> >, key_type为int, value_type为vector<int>


-------------------------------------------------------------------------------------------------

添加元素

添加元素可以通过insert函数添加键--值对,或者通过下标操作符给获取的元素赋值,但是一个map容器中不能有重复的键,

因此当插入的键--值对或通过下表获取的键--值对中的键有重复时影响了插入的效果。

可以确定的是当用下标获取元素时可以作为左值,即可被赋值,当map中有同键名的元素时,对此左值所操作的结果作用于这个元素,

当map中不含此键名的元素时则为插入一个新的元素。

eg.

map<string, int> word_count;               //统计单词出现次数

word_count["hello"] = 1;                       //若map中无此单词则插入次单词,否则将该单词出现次数置为1


-------------------------------------------------------------------------------------------------

p312

习题10.9   编写程序统计并输出所读入单词的出现次数


#include <iostream>

#include <string>

#include <map>

using namespace std;

 

int main()

{

map<string, unsigned int> wordTimes;               //int 默认为0

string str;

cout<<"input"<<endl;

 

while (cin>>str)

{

wordTimes[str] ++;                                    //如果str没出现过则插入pair<const str, int>,否则 int++

 

for (map<string, unsigned int>::const_iterator iter = wordTimes.begin(); iter != wordTimes.end(); ++ iter)

{

cout<<(*iter).first<<"  "<<iter->second<<endl;

}  

cout<<endl;

return 0;

}


//运行结果

C++ Primer笔记   map - 大灰狼 - 大灰狼 的博客

从运行结果可以很直观的发现,还有一个特点:输出的时候,map按照key_type(键升序)输出。


 



原创粉丝点击