You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
1.5 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

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