#include <iostream>
#include <unordered_map>
#include <string>
int main() {
// 创建一个 unordered_map,键为字符串,值为整数
std::unordered_map<std::string, int> umap;
// 插入元素
umap["apple"] = 1;
umap["banana"] = 2;
umap["orange"] = 3;
// 查找元素
auto it = umap.find("banana");
if (it != umap.end()) {
std::cout << "Found: " << it->first << " with value " << it->second << std::endl;
} else {
std::cout << "Not found" << std::endl;
}
// 遍历 unordered_map
for (const auto& pair : umap) {
std::cout << pair.first << ": " << pair.second << std::endl;
}
// 删除元素
umap.erase("apple");
// 检查元素是否存在
if (umap.count("apple") == 0) {
std::cout << "apple is not in the map" << std::endl;
}
return 0;
}
#include <unordered_map> 和 #include <string> 是为了使用 std::unordered_map 和 std::string。std::unordered_map<std::string, int> umap; 创建了一个无序映射(哈希表),键是 std::string 类型,值是 int 类型。umap["key"] = value; 的方式插入键值对。find 方法查找指定键的元素,并通过迭代器访问其值。for 循环遍历所有键值对。erase 方法删除指定键的元素。count 方法检查某个键是否存在于 unordered_map 中。上一篇:c++ readqueue
下一篇:c++while
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站