1、map被定义为一对数值,其中的key通常是个字符串,扮演索引的角色,另一个数值为value。字典便是map的一个不错的实体。
#include<map> #include<string> map<string, int> words; words["aaaa"] =1; string tword; while(cin>>tword) words[tword]++;
2、查询map内是否存在某个key,有三种方法。
1. int count = 0;
if(!(count = words["aaa"]))
//aaa并不存在words map 内。
缺点:如果我们用来索引的那个key并不存在于map内,则那个key会自动被加入map中。而其相应的value会被设为所属型别的默认值。
2. find()函数。
words.find("aaa");\
int count = 0; map<string, int>::iterator it; it = words.find("aaa"); if(it != words.end()) count = it.sencond;
3. count()函数。