用c++创建一个哈希表
时间: 2024-06-08 08:03:46 浏览: 24
在C++中,创建一个哈希表(也称为关联数组或哈希映射)通常使用`std::unordered_map`容器,它是C++标准库中的一个模板类,提供了高效的数据存储和查找。以下是一个简单的步骤来创建和使用一个哈希表:
1. 包含头文件:
```cpp
#include <iostream>
#include <unordered_map>
```
2. 声明并实例化哈希表,指定键值对类型:
```cpp
std::unordered_map<std::string, int> myHashTable;
```
这里我们用`std::string`作为键(key),`int`作为值(value)。
3. 插入元素:
```cpp
myHashTable["apple"] = 10;
myHashTable["banana"] = 20;
```
4. 访问和修改元素:
```cpp
int valueForApple = myHashTable["apple"]; // 值为10
myHashTable["apple"] = 15; // 修改苹果的值
```
5. 删除元素(如果支持):
```cpp
myHashTable.erase("banana"); // 删除香蕉条目
```
6. 遍历哈希表:
```cpp
for (const auto& pair : myHashTable) {
std::cout << "Key: " << pair.first << ", Value: " << pair.second << std::endl;
}
```
相关问题
C++哈希表创建链接表
C++中创建哈希表并使用链接表解决散列冲突的方法如下所示:
```cpp
#include <iostream>
#include <list>
class HashTable {
private:
static const int tableSize = 10; // 哈希表的大小
std::list<int> table[tableSize]; // 使用链表作为哈希表的每个槽
public:
int hashFunction(int key) {
return key % tableSize; // 哈希函数,取余操作
}
void insert(int key) {
int index = hashFunction(key); // 计算哈希值
table[index].push_back(key); // 将元素插入对应的链表中
}
void display() {
for (int i = 0; i < tableSize; i++) {
std::cout << "Index " << i << ": ";
for (auto it = table[i].begin(); it != table[i].end(); ++it) {
std::cout << *it << " ";
}
std::cout << std::endl;
}
}
};
int main() {
HashTable hashTable;
hashTable.insert(55);
hashTable.insert(2);
hashTable.insert(108);
hashTable.display();
return 0;
}
```
这段代码创建了一个大小为10的哈希表,使用链表来解决散列冲突。`hashFunction`函数使用取余操作来计算哈希值,然后将元素插入对应的链表中。`display`函数用于显示哈希表的内容。
运行上述代码,输出结果如下:
```
Index 0:
Index 1:
Index 2: 2
Index 3:
Index 4:
Index 5: 55
Index 6:
Index 7:
Index 8:
Index 9: 108
```
可以看到,元素55和108被插入到了哈希表的索引5和索引9的链表中。
哈希表的创建c++
哈希表是一种常用的数据结构,可以快速地存储和查找数据。下面是在 C++ 中创建哈希表的基本代码:
```c++
#include <iostream>
#include <unordered_map>
using namespace std;
int main() {
// 创建一个哈希表
unordered_map<string, int> myMap;
// 向哈希表中添加元素
myMap["apple"] = 3;
myMap["banana"] = 5;
myMap["orange"] = 2;
// 访问哈希表中的元素
cout << "apple: " << myMap["apple"] << endl;
cout << "banana: " << myMap["banana"] << endl;
cout << "orange: " << myMap["orange"] << endl;
return 0;
}
```
在上面的代码中,我们首先包含了 `<unordered_map>` 库,然后创建了一个 `unordered_map<string, int>` 类型的哈希表 `myMap`,其中 `string` 表示键的类型,`int` 表示值的类型。
然后,我们向哈希表中添加了三个元素,分别是 `"apple"`、`"banana"` 和 `"orange"`,对应的值分别是 `3`、`5` 和 `2`。
最后,我们通过 `myMap["apple"]` 等方式访问了哈希表中的元素,输出了相关信息。
需要注意的是,哈希表中的元素并不是按照添加的顺序存储的,而是根据键的哈希值进行存储和查找的。因此,哈希表的访问操作的时间复杂度是常数级别的,具有很高的效率。