温馨提示×

在VisualC中使用HashTable集合

c
小云
85
2023-09-08 07:00:31
栏目: 编程语言

在Visual C++中,可以使用STL库中的unordered_map来实现哈希表集合。unordered_map是一个使用哈希表实现的关联容器,可以快速地查找、插入和删除元素。

下面是一个使用unordered_map的示例代码:

#include <iostream>
#include <unordered_map>
int main() {
// 创建一个unordered_map集合
std::unordered_map<int, std::string> hashTable;
// 向哈希表中插入元素
hashTable.insert({1, "Apple"});
hashTable.insert({2, "Banana"});
hashTable.insert({3, "Orange"});
// 查找元素
auto it = hashTable.find(2);
if (it != hashTable.end()) {
std::cout << "Key: " << it->first << ", Value: " << it->second << std::endl;
}
// 遍历哈希表中的所有元素
for (const auto& pair : hashTable) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
return 0;
}

在上面的示例中,我们首先创建了一个unordered_map集合,使用insert函数向哈希表中插入元素。然后使用find函数查找特定的键,并输出对应的值。最后使用for循环遍历哈希表中的所有元素,并输出它们的键和值。

请注意,unordered_map中的元素是无序的,插入和查找操作的平均时间复杂度为O(1)。

0