用c++写一个顺序结构的查找表
时间: 2024-01-04 18:01:53 浏览: 35
以下是使用 C++ 实现一个顺序结构的查找表的示例代码:
```
#include <iostream>
using namespace std;
#define MAX_SIZE 100 // 表的最大长度
typedef struct {
int key; // 关键字
// 其他数据项
} ElemType;
class SSTable {
public:
SSTable() { length = 0; } // 初始化表长为0
void insert(int k) { // 插入关键字为k的数据项
if (length >= MAX_SIZE) { // 表满,插入失败
cout << "Insert failed: table is full." << endl;
return;
}
elem[length].key = k;
length++;
}
int search(int k) { // 查找关键字为k的数据项,返回其下标,没有则返回-1
for (int i = 0; i < length; i++) {
if (elem[i].key == k) {
return i;
}
}
return -1;
}
void print() { // 打印表中元素
for (int i = 0; i < length; i++) {
cout << elem[i].key << " ";
}
cout << endl;
}
private:
ElemType elem[MAX_SIZE]; // 存储空间
int length; // 表长
};
int main() {
SSTable table;
table.insert(3);
table.insert(5);
table.insert(1);
table.insert(7);
table.print();
int index = table.search(5);
if (index == -1) {
cout << "Not found." << endl;
} else {
cout << "Found at index " << index << endl;
}
index = table.search(9);
if (index == -1) {
cout << "Not found." << endl;
} else {
cout << "Found at index " << index << endl;
}
return 0;
}
```
在这个示例代码中,我们使用了一个 `SSTable` 类来表示顺序结构的查找表。它包含了插入、查找和打印表中元素的方法。在 `main()` 函数中,我们创建了一个 `SSTable` 对象,并向其中插入了一些数据项,然后进行了查找操作。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)