c++哈希表查询方法
时间: 2024-01-04 09:18:09 浏览: 28
C++中哈希表的查询方法主要有以下两种:
1.使用find()函数进行查询
```c++
// 查找key所在的元素
// 找到:返回元素的迭代器。通过迭代器的first和second属性获取值
// 没找到:返回unordered_map::end
unordered_map<string, double> mymap;
string input = "mom";
unordered_map<string, double>::const_iterator got = mymap.find(input);
if(got == mymap.end())
cout << "not found";
else
cout << got->first << " is " << got->second;
```
2.使用[]运算符进行查询
```c++
// 查找key所在的元素
// 找到:返回元素的值
// 没找到:插入一个新元素,值为默认值,返回新元素的值
unordered_map<string, double> mymap;
string input = "mom";
double value = mymap[input];
if(value == 0)
cout << "not found";
else
cout << input << " is " << value;
```
相关问题
C++ 哈希表使用方法
C++中可以使用STL中的unordered_map来实现哈希表,下面是使用方法:
1. 头文件包含
```c++
#include <unordered_map>
```
2. 定义哈希表
```c++
std::unordered_map<key_type, value_type> my_map;
```
其中,key_type为键的类型,可以是整型、字符型等等;value_type为值的类型,可以是整型、字符型、自定义结构体等等。
3. 插入元素
```c++
my_map.insert(std::make_pair(key, value));
```
其中,key为键,value为值。
4. 查找元素
```c++
auto it = my_map.find(key);
if(it != my_map.end()){
//找到了
value = it->second;
}
else{
//未找到
}
```
其中,it为迭代器,可以通过it->second获取对应的值。如果未找到,则it等于my_map.end()。
5. 删除元素
```c++
my_map.erase(key);
```
其中,key为要删除的元素对应的键。
哈希表的使用方法就介绍到这里,需要注意的是,哈希表的元素是无序的,如果需要有序,则可以考虑使用map容器。
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的链表中。