#1012. STL之map
STL之map
map
是一种用于存储键值对的数据结构,可以认为是计数数组的一种升级,哈希的替代用法。
头文件:map
创建容器:map<键 key 类型, 值 value 类型> 容器名称
常用成员函数
map<string, int> mp;
mp.size() 表示键的个数
mp.find(key) 搜索这个键,若存在则返回其迭代器
mp.clear() 表示清空容器元素
mp.empty() 查看容器是否为空
mp.count(t) 查看键为 t 的是否存在
Example
#include <iostream>
#include <map>
using namespace std;
int main () {
map<string, int> mp;
for (int i=1; i<=4; i++) {
string name;
int age;
cin >> name >> age;
mp[name] = age;
}
string sName;
cout << "输入想要查询的姓名:";
cin >> sName;
if (mp.find(sName) != mp.end()) {
cout << "找到: " << sName << ":" << mp[sName] << endl;
} else {
cout << "此姓名不存在" << endl;
}
cout << "遍历:" << endl;
map<string, int>::iterator it;
for (it = mp.begin(); it != mp.end(); it++) {
cout << it->first << ":" << it->second << endl;
}
cout << "auto 遍历: " << endl;
for (auto it : mp) {
cout << it.first << ":" << it.second << endl;
}
return 0;
}
简单练习
👆计数数组会炸内存,因为数据范围太大,因此用 map 减少需要记录的数字种类数
- 以下对
map<char, int> mp;添加键值对正确的是 ?
{{ select(1) }}
mp['m'] = 20;mp["m"] = 20;
Related
In following homework: