用cpp语言制作一个程序,要求写出完整的代码,该程序用桶的散列技术实现查找和插入功能
时间: 2023-02-05 14:25:02 浏览: 48
这是一个使用 C++ 实现桶的散列技术的简单示例:
```cpp
#include <iostream>
#include <vector>
// 桶的散列表类型
template <typename T>
class HashTable
{
private:
// 桶的数量
static const int BUCKET_COUNT = 10;
// 内部类型:桶的节点
struct Node
{
T value;
Node* next;
Node(T val) : value(val), next(nullptr) {}
};
// 桶的数组
std::vector<Node*> buckets;
public:
HashTable()
{
// 初始化桶的数组
for (int i = 0; i < BUCKET_COUNT; ++i)
{
buckets.push_back(nullptr);
}
}
// 计算哈希值
int hash(T value)
{
return value % BUCKET_COUNT;
}
// 查找值
bool find(T value)
{
// 计算哈希值
int h = hash(value);
// 查找值
Node* node = buckets[h];
while (node != nullptr)
{
if (node->value == value)
{
return true;
}
node = node->next;
}
// 未找到值
return false;
}
// 插入值
void insert(T value)
{
// 计算哈希值
int h = hash(value);
// 创建新节点
Node* newNode = new Node(value);
newNode->next = buckets[h];
buckets[h] = newNode;
}
};
int main()
{
HashTable<int> hashTable;
// 插入值
hashTable.insert(10);
hashTable.insert(20);
hashTable.insert(30);
// 查找值
std::cout << hashTable.find(10) << std::endl; // 输出 1
std::cout << hashTable.find(20) << std::endl; // 输出 1
std::cout << hashTable.find(30) << std::endl; // 输出 1
std::cout << hashTable.find(40) << std::endl; // 输出 0
return 0;
}
```
在这个示例