c++实现哈希表查找
哈希表是一种高效的数据结构,可以实现快速的查找操作。下面是用C++实现哈希表查找的示例代码:
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
// 创建哈希表
unordered_map<string, int> hashTable;
// 插入元素
hashTable["apple"] = 10;
hashTable["banana"] = 20;
hashTable["orange"] = 30;
// 查找元素
string key = "banana";
if (hashTable.find(key) != hashTable.end()) {
cout << key << " is found, value is " << hashTable[key] << endl;
} else {
cout << key << " is not found" << endl;
}
key = "pear";
if (hashTable.find(key) != hashTable.end()) {
cout << key << " is found, value is " << hashTable[key] << endl;
} else {
cout << key << " is not found" << endl;
}
return 0;
}
在上面的代码中,我们使用了unordered_map类创建了一个哈希表。然后,我们向哈希表中插入了一些元素。接着,我们使用find函数查找哈希表中是否存在某个元素,如果存在就输出其值,否则输出不存在。在实际使用中,我们可以根据具体的需求来选择不同的哈希表实现,以及不同的哈希函数和冲突解决方法。
原文地址: https://www.cveoy.top/t/topic/bwgy 著作权归作者所有。请勿转载和采集!