#Z4006. map 的使用
map 的使用
#include <iostream>
#include <string>
using namespace std;
int main() {
return 0;
}
-
引入需要的头文件map,在代码头部写下
#include <map>
-
创建一个map。 在main函数里面通过
map<string, int> dict
来定义一个从string到int的map,初始为空。map<string, int> dict;
-
把Tom、Jone、Mary依次插入到map并一一对应的赋值。 在main函数中接着写下
dict["Tom"] = 1; dict["Jone"] = 2; dict["Mary"] = 3;
-
接下来我们查看map中 Mary对应的 value 值,先判断一下map中是否有Mary。
如果有的话,我们输出以后改变Mary对应的值为 5。 在main函数中接着写下
if (dict.count("Mary")) { cout << "Mary is in class " << dict["Mary"] << endl; dict["Mary"] = 5; }
-
点击运行看看效果。
-
接下来我们学习map的遍历操作。
还是通过迭代器来操作,迭代器指向的是一个pair对象,first成员对应的是key,second成员对应的是value。 在main函数中接着写下
map<string,int>::iterator it; for (it = dict.begin(); it != dict.end(); it++) { cout << it->first << " is in class " << it->second << endl; }
-
输出完成以后,我们顺便清空这个map。
调用dict.clear()进行清空,并输出dict中的元素个数。 在return 0;上面写下
dict.clear(); cout << dict.size() << endl;
-
运行 看看效果。