通过前面的学习我们知道,map 容器模板类中提供有 operator[ ] 和 insert() 这 2 个成员方法,而值得一提的是,这 2 个方法具有相同的功能,它们既可以实现向 map 容器中添加新的键值对元素,也可以实现更新(修改)map 容器已存储键值对的值。
举个例子(程序一):
#include <map> //map#include <string> //string#include <iostream>using namespace std;
int main(){ std::map<string, string> mymap; //借用 operator[] 添加新键值对 mymap["player_01"] = "{\"username\":\"Bear\",\"deviceid\":\"baf8700ac280467fcaf581520dc510ebf1c61c42_3400_MS - 7C02(Micro - Star International Co., Ltd)\"}"; cout << string("old mymap:") << mymap["player_01"] << endl; //借用 operator[] 更新某个键对应的值 mymap["player_01"] = "{\"username\":\"Horse\",\"deviceid\":\"caf8700ac280467fcaf581520dc510ebf1c61c42_3400_MS - 7C02(Micro - Star I