#include using namespace std; /* 功能:输出打印map 作者:黄海 时间:2019-10-29 */ void printMap(map _map) { map::iterator iter = _map.begin(); for (; iter != _map.end(); iter++) { cout << iter->first << ' ' << iter->second << endl; } cout << endl; } /* 功能:判断数据是不是存在map中 作者:黄海 时间:2019-10-29 */ bool isExist(map _map, int a) { map::iterator iter = _map.find(a); if (iter != _map.end()) { return 1; } else { return 0; } } /* 功能:从map中删除一个元素 作者:黄海 时间:2019-10-29 */ void deleteMapByKey(map& _map, int a) { //注意这里的&表示按引用实参 ,允许函数改变实参的值 //根据键值删除 _map.erase(a); } /* 功能:修改map中的一个元素数据 作者:黄海 时间:2019-10-29 */ void updateForMap(map& _map, int key, int value) { //注意这里的&表示按引用实参 ,允许函数改变实参的值 map::iterator iter = _map.find(key); if (iter != _map.end()) { iter->second = value; return; } } int main() { //字典map map _map; //插入元素 for (int i = 1; i <= 10; i++) { pair value(i, i); _map.insert(value); } //打印是不是存在数字3 cout << "是否存在数字3:" << isExist(_map, 3) << endl; //尝试删除元素3 deleteMapByKey(_map, 3); //再次打印是不是存在数字3 cout << "是否存在数字3:" << isExist(_map, 3) << endl; //输出map cout << "元素修改前的map" << endl; printMap(_map); //修改数据 updateForMap(_map, 6, 10); //输出map cout << "元素修改后的map" << endl; printMap(_map); return 0; }