用C++写
时间: 2023-08-16 21:08:35 浏览: 37
好的,下面是一个用C++实现的程序,实现了上述功能:
```c++
#include <iostream>
#include <vector>
using namespace std;
// 定义顺序表类
class SeqList {
public:
SeqList(vector<int> data = {}) : data(data) {}
int length() { return data.size(); }
int& operator[](int index) { return data[index]; }
void insert(int index, int value) { data.insert(data.begin() + index, value); }
void remove(int index) { data.erase(data.begin() + index); }
private:
vector<int> data;
};
int main() {
// 输入元素,以?结束
vector<int> data;
cout << "请输入你想建立的顺序表的元素,以?结束:" << endl;
int value;
while (cin >> value) {
data.push_back(value);
char c = getchar();
if (c == '?') break;
}
// 建立顺序表
SeqList seq(data);
cout << "你建立的顺序表为:";
for (int i = 0; i < seq.length(); i++) {
cout << seq[i] << "—>";
}
cout << endl;
// 输出顺序表长度
cout << "顺序表的长度为:" << seq.length() << endl;
// 查找元素
cout << "输入你想查找的元素:";
cin >> value;
int index;
for (index = 0; index < seq.length(); index++) {
if (seq[index] == value) {
cout << "你查找的元素为" << value << ",序位为" << index + 1 << endl;
break;
}
}
if (index == seq.length()) {
cout << "未找到元素" << value << endl;
}
// 查找序位
cout << "输入你想查找的元素序位:";
cin >> index;
if (index < 1 || index > seq.length()) {
cout << "序位超出范围!" << endl;
} else {
value = seq[index-1];
cout << "你查找的元素为:" << value << endl;
}
// 插入元素
cout << "输入你想插入的元素以及序位:<用逗号隔开>:";
cin >> value >> index;
if (index < 1 || index > seq.length() + 1) {
cout << "序位超出范围!" << endl;
} else {
seq.insert(index-1, value);
cout << "插入后顺序表为:";
for (int i = 0; i < seq.length(); i++) {
cout << seq[i] << "—>";
}
cout << endl;
}
// 删除元素
cout << "请输入你想删除的元素序位:";
cin >> index;
if (index < 1 || index > seq.length()) {
cout << "序位超出范围!" << endl;
} else {
seq.remove(index-1);
cout << "删除后的顺序表为:";
for (int i = 0; i < seq.length(); i++) {
cout << seq[i] << "—>";
}
cout << endl;
}
return 0;
}
```
希望对你有所帮助!