Files
python/C++专题课程/STL基础知识/键值对使用.cpp
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

85 lines
1.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#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;
}