#include <iostream>
#include <unordered_map>
#include <string>
int main() {
// 创建一个哈希表,键为字符串,值为整数
std::unordered_map<std::string, int> hash_table;
// 向哈希表中插入键值对
hash_table["apple"] = 1;
hash_table["banana"] = 2;
hash_table["orange"] = 3;
// 查找键对应的值
std::string key = "banana";
if (hash_table.find(key) != hash_table.end()) {
std::cout << "Value of " << key << " is " << hash_table[key] << std::endl;
} else {
std::cout << key << " not found in hash table" << std::endl;
}
// 遍历哈希表并打印所有键值对
for (const auto& pair : hash_table) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}
引入头文件:
#include <iostream>
:用于输入输出操作。#include <unordered_map>
:用于创建哈希表(无序映射)。#include <string>
:用于处理字符串。创建哈希表:
std::unordered_map
创建一个哈希表 hash_table
,其中键是 std::string
类型,值是 int
类型。插入键值对:
hash_table["key"] = value;
的方式向哈希表中插入键值对。查找键对应的值:
hash_table.find(key)
方法查找键是否存在于哈希表中。如果存在,则返回对应的迭代器;否则返回 hash_table.end()
。hash_table[key]
获取键对应的值。遍历哈希表:
for (const auto& pair : hash_table)
遍历哈希表中的每个键值对,并打印出来。这段代码展示了如何使用 C++ 中的 std::unordered_map
实现哈希表的基本操作,包括插入、查找和遍历。
上一篇:c++泛型
下一篇:c++ 格式化字符串
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站