通過前面的學習我們知道,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