建立一个顺序表,查找表中第1个与指定元素相等的元素。若存在,则返回该元素在表中的位置(下标);否则返回-1。完整程序
时间: 2024-03-10 17:48:29 浏览: 28
好的,下面是一个完整的程序,包括顺序表的建立和查找函数的实现:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义顺序表类
class SeqList {
private:
int *arr; // 数组指针
int len; // 表长度
public:
SeqList(int size); // 构造函数
~SeqList(); // 析构函数
int search(int x); // 查找函数
void print(); // 打印函数
};
// 构造函数,初始化数组和长度
SeqList::SeqList(int size) {
arr = new int[size];
len = size;
}
// 析构函数,释放内存
SeqList::~SeqList() {
delete[] arr;
}
// 查找函数,返回第一个与指定元素相等的元素下标,如果不存在则返回-1
int SeqList::search(int x) {
for (int i = 0; i < len; i++) {
if (arr[i] == x) {
return i;
}
}
return -1;
}
// 打印函数,输出数组元素
void SeqList::print() {
for (int i = 0; i < len; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
// 测试程序
int main() {
int size = 5; // 数组长度
SeqList list(size); // 创建顺序表对象
list.print(); // 输出初始数组
int x = 3; // 要查找的元素
int pos = list.search(x); // 查找元素的下标
if (pos == -1) {
cout << "元素 " << x << " 不存在" << endl;
} else {
cout << "元素 " << x << " 的下标是 " << pos << endl;
}
return 0;
}
```
这个程序中,我们定义了一个 `SeqList` 类来表示顺序表,包含了数组指针和长度两个私有成员变量,以及构造函数、析构函数、查找函数和打印函数四个公有成员函数。
在 `main()` 函数中,我们创建了一个 `SeqList` 对象 `list`,并调用了它的打印函数和查找函数。如果要查找的元素存在于数组中,则输出它的下标,否则输出元素不存在的提示信息。
相关推荐
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)