unordered_map
作者:
狂扁小子
,
2024-03-19 17:41:06
,
所有人可见
,
阅读 16
unordered_map
#include <iostream>
#include <string>
#include <unordered_map>
using namespace std;
int main() {
// 创建一个unordered_map,键类型为string,值类型为int
unordered_map<string, int> map;
// 插入数据
map["apple"] = 5;
map["banana"] = 8;
map["cherry"] = 3;
// 访问数据
cout << "apple has value: " << map["apple"] << endl;
// 检查键是否存在并访问
string key = "banana";
if (map.find(key) != map.end()) {
cout << key << " exists with value: " << map[key] << endl;
} else {
cout << key << " does not exist." << endl;
}
// 遍历unordered_map中的所有键值对
cout << "All items in the unordered_map:" << endl;
for (const auto &pair : map) {
cout << pair.first << " has value: " << pair.second << endl;
}
// 删除一个元素
map.erase("cherry");
// 再次遍历以确认删除
cout << "After erasing 'cherry':" << endl;
for (const auto &pair : map) {
cout << pair.first << " has value: " << pair.second << endl;
}
return 0;
}