本文中的一些重要概念摘自C语言中文网
链接:http://c.biancheng.net/view/391.html
上一节中,我们了解了multimap,它的每个元素都是一个pair模板类对象,也就是键值对,但是它的键名是可以相同的,比如上节中的例子,将学生的分数作为键名,就有可能有多个值相同的键名。这一节我们要介绍的是map,与multimap不同的是,map中的键名不能重复。
同样,要使用STL中的map,我们要包含头文件map
multimap 有的成员函数,map 都有。此外,map 还有成员函数 operator[]:
T & operator[] (Key k);
该成员函数返回 first 值为 k 的元素的 second 部分的引用。如果容器中没有元素的 first 值等于 k,则自动添加一个 first 值为 k 的元素。如果该元素的 second 成员变量是一个对象,则用无参构造函数对其初始化。
下面是测试程序:
#include<iostream>
#include<map>
#include<string>
using namespace std;
template<class T1, class T2>
ostream& operator<<(ostream &o, pair<T1, T2> p)
{
o << p.first << " " << p.second << endl;
return o;
}
template<class T>
void Print(T first, T last)
{
for(; first != last; ++first)
{
cout << *first;
}
cout << endl;
}
typedef map<string, int> mymap;
int main()
{
mymap people;
people.insert(make_pair("jason", 22));
cout << "after insert a person jason:";
Print(people.begin(), people.end());
cout << "the man is " << people["jason"] << "years old!" << endl;
people["tom"] = 23;
Print(people.begin(), people.end());
cout << make_pair("jerry", 19) << endl;
return 0;
}程序输出结果:

京公网安备 11010502036488号