Map
1 使用
1 声明
/*声明map*/
map<int, string> myMap = {{1, "Apple"}, {2, "Banana"}, {3, "Orange"}};
2 插入元素
myMap.insert(make_pair(4, "Graphes"));
3 通过访问键查找和访问元素
cout << myMap[2] << endl;
4 遍历并打印map中元素
for(const auto& pair : myMap) {
cout << "Key is: " << pair.first << ", Value is: " << pair.second << endl;
}
5 删除元素
myMap.erase(3);
6 判断指向某个键指向的键值对是否存在
if(myMap.count(3) == 0) {
cout << "Key 3 not found" << endl;
}
7 清空map
myMap.clear()
8 完整代码
#include <bits/stdc++.h>
using namespace std;
int main() {
/*声明map*/
map<int, string> myMap = {{1, "Apple"}, {2, "Banana"}, {3, "Orange"}};
/*插入元素*/
myMap.insert(make_pair(4, "Grapes"));
/*通过访问键查找和访问元素*/
cout << myMap[2] << endl;
/*遍历并打印map中元素*/
for(const auto& pair : myMap) { //const auto& pair:用于遍历map的迭代器
cout << "Key is " << pair.first << ", Value: " << pair.second << endl;
}
/*删除元素*/
myMap.erase(3); //这个是将整个key = 3的键值对删除了
cout << "After delete key 3, the new map is:" << endl;
for(const auto& pair : myMap) {
cout << "Key is: " << pair.first << ", Value is: " << pair.second << endl;
}
/*判断指向某个键指向的键值对是否存在*/
if(myMap.count(3) == 0) {
cout << "Key 3 not found" << endl;
}
/*清空map*/
myMap.clear();
if(myMap.empty()) {
cout << "Map is empty" << endl;
}
system("pause");
return 0;
}
2 运用
2.1 主要思路:
1 使用map,其中每读取一个元素作为键,同时将这个键对应的值递增1
2 计算最少删除的元素数量时,如果当前键大于值,那么就将这个键清零;如果值大于键,那么就删除多余的
2.2 代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
map<int, int> myMap;
int n;
scanf("%d", &n);
int data;
for(int i = 0; i < n; i++) {
scanf("%d", &data);
myMap[data]++;
}
int count = 0;
for(const auto& pair : myMap) {
cout << pair.first << ' ' << pair.second << endl;
if(pair.first < pair.second) {
count += (pair.second - pair.second);
}
else if(pair.first > pair.second) {
count += pair.second;
}
}
cout << count << endl;
return 0;
}