map 对象的元素是键值对(key,value),每个key对应一个value, map默认中按key定义的 “ < ” 排序。
key是一个const 对象不可以改变,其类型为map<k,v>::key_type;
value 是一个非const对象,其类型为map<k,v>::mapped_type;
访问map可以用迭代器访问也可以用下标访问:
1、用迭代器访问:
map<k,v>::iterator iter = m.begin();......
这时候对迭代器解引用会得到map容器中一个map<k,v>::value_type 类型的值,对于map容器来说该值是pair类型,再标准库中pair在utility 中声明,pair<first,second> first 为const 对象保存key;second为非const对象,保存value。
在上面的例子中为pair<const string, int>。因此可以使用迭代器来访问map中的所有值。
2、用下下标访问
例如在编写下面程序时:
1 map<string, int> word_count; // empty
2 // insert default initialized element with key "SK"; then assign 1 to its value
3 word_count["SK"] = 1;
该程序会在map中查找"SK"键,如果查找到则将"SK" 对应的值赋值为 1。但是word_count 初始为空,并不存在"SK"键,因此 word_count["SK"] = 1;将创建一个"SK"键,并将其对应的值初始化为1.
利用这个性质我们可以写一个之前用数组和其他方式实现起来比较麻烦的单词统计程序:
#include<iostream>
#include<map>
#include<string>
using namespace std;
int main()
{
map<string,int> wordCount;
string word;
while(cin>>word)
{
++wordCount[word];
}
map<string,int>::iterator iter;
for(iter=wordCount.begin();iter!=wordCount.end();iter++)
{
cout<<iter->first<<"--->"<<iter->second<<endl;
}
}
测试用例:
aaa bbb c c aaa bbb
^Z
aaa--->2
bbb--->2
c--->2
可以看到key是按照字典顺序排列的。