C++中的哈希表可以使用标准库中的unordered_map
容器来实现。unordered_map
容器使用哈希函数来将键值映射到存储桶中,以实现快速的插入、查找和删除操作。
以下是使用unordered_map
容器实现哈希表的示例代码:
#include <iostream>
#include <unordered_map>
#include <string>
using namespace std;
int main() {
// 创建一个unordered_map对象,键类型为string,值类型为int
unordered_map<string, int> hashMap;
// 向哈希表中插入键值对
hashMap["apple"] = 1;
hashMap["banana"] = 2;
hashMap["orange"] = 3;
// 查找键值对
if (hashMap.find("banana") != hashMap.end()) {
cout << "The value of banana is " << hashMap["banana"] << endl;
}
else {
cout << "The key banana is not found in the hash table." << endl;
}
// 遍历哈希表中的所有键值对
for (auto& kv : hashMap) {
cout << kv.first << " : " << kv.second << endl;
}
return 0;
}
在上面的代码中,我们首先创建了一个unordered_map
对象,并指定了键类型为string
,值类型为int
。然后,我们使用[]
运算符向哈希表中插入了三个键值对。接着,我们使用find()
函数查找了键为"banana"的键值对,并输出了对应的值。最后,我们使用范围for循环遍历了哈希表中的所有键值对,并输出了它们的键和值。