<map>
是键值对的集合,唯一的约束是键类型必须支持 < 操作符。
map<k,v>::key_type 键类型
map<k,v>::mapped_type 关联值类型
map<k,v>::value_type pair<k,v>类型
与vector不同的是用下标访问不存在的元素将导致在map容器中添加一个新的元素,它的键即为下标值
带有一个键-值的insert版本将返回一个值:包含一个迭代器和一个bool值的pair对象,其中迭代器指向map中具有相应键的元素,而bool值则表示是否插入了该元素。若该键已在容器中,则其关联的值保持不变,返回的bool值为false;如果该键不在容器中则插入新元素,且bool值为true。
//单词统计程序
map<string, int> word_count;
string word;
while(cin>>word)
{
pair<map<string, int>::iterator, bool> ret =
word_count.insert(make_pair(word,1));
if(!ret.second)
++ret.first->second;
}
查找并读取map中的元素
1、count
//
int occurs = 0;
if(word_count.count ("foor_bar") )
occurs = word_count["foor_bar"];
2、find
//
int occurs = 0;
map<string, int>::iterator it = word_count.find("foorbar");
if(it != word_count.end())
occurs = it -> second;
使用迭代器遍历map容器时,迭代器指向的元素按键顺序的升序排列。