#Z4006. map 的使用

map 的使用

#include <iostream>
#include <string>
using namespace std;
int main() {
  

    return 0;

}
  1. 引入需要的头文件map,在代码头部写下 #include <map>

  2. 创建一个map。 在main函数里面通过map<string, int> dict来定义一个从string到int的map,初始为空。 map<string, int> dict;

  3. 把Tom、Jone、Mary依次插入到map并一一对应的赋值。 在main函数中接着写下

    dict["Tom"] = 1;
    dict["Jone"] = 2;
    dict["Mary"] = 3;
    
  4. 接下来我们查看map中 Mary对应的 value 值,先判断一下map中是否有Mary。

    如果有的话,我们输出以后改变Mary对应的值为 5。 在main函数中接着写下

    if (dict.count("Mary")) {
        cout << "Mary is in class " << dict["Mary"] << endl;
        dict["Mary"] = 5;
    }
    
  5. 点击运行看看效果。

  6. 接下来我们学习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;
    }
    
  7. 输出完成以后,我们顺便清空这个map。

    调用dict.clear()进行清空,并输出dict中的元素个数。 在return 0;上面写下

    dict.clear();
    cout << dict.size() << endl;
    
  8. 运行 看看效果。