You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
2.8 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
//顺序表最大输入范围
const int N = 100;
// C++ 类构造函数 & 析构函数
// https://www.runoob.com/cplusplus/cpp-constructor-destructor.html
//声明一个模板虚拟类型名为T
template<class T>
class setlist { //类模板名为setlist
//私有
private:
T data[N]; //存放数据的数组date;
int length; //线性表长度;
//公有
public:
//空构造函数
setlist() {
length = 0; // 初值
}
//构造函数
setlist(T a[], int n) {
if (n > N) throw "装不下,参数非法";
for (int i = 0; i < n; i++) {
data[i] = a[i];//保存到内部的数组中
length = n;
}
}
// 析构函数:类的析构函数是类的一种特殊的成员函数,它会在每次删除所创建的对象时执行。
// 析构函数的名称与类的名称是完全相同的,只是在前面加了个波浪号(~)作为前缀,它不会返回任何值,
// 也不能带有任何参数。析构函数有助于在跳出程序(比如关闭文件、释放内存等)前释放资源。
~setlist() {}
//对外获取长度的函数调用入口
int Length() { return length; }
//按索引定位值的方法
T Get(int i) {
if (i < 1 || i > length) throw "查找位置非法";
else
return data[i - 1];
}
//按值定位索引的方法
int Locate(T x) {
for (int i = 0; i < length; i++)
if (data[i] == x) return i + 1;
return 0;
}
//插入一个对象
void insert(int i, T x) {
if (length >= N) throw "上溢";
if (i < 1 || i > length + 1) throw "位置异常";
//向后移动一个位置
for (int j = length; j >= i; j--) {
data[j] = data[j - 1];
}
//将插入的对象放到指定的位置上
data[i - 1] = x;
//修改长度属性
length++;
}
//删除一个对象:按位置删除
T Delete(int i) {
if (length == 0)throw "下溢";
if (i < 1 || i > length)throw "位置异常";
T x = data[i - 1]; //备份一个出来,用于返回
//开始从这个位置到最后,一个个向左移动过来
for (int j = i; j < length; j++)
data[j - 1] = data[j];
//长度属性-1
length--;
//返回这个对象
return x;
}
//输出顺序表
void PrintList() {
for (int i = 0; i < length; i++)
cout << data[i];
cout << endl;
}
};
int main() {
//数组test
int test[5] = {2, 1, 3, 4, 5};
//通过构造函数进行构建顺序表
setlist<int> a = setlist<int>(test, 5);
//输出顺序表
a.PrintList();
//测试各个内置方法
cout << "长度为:" << a.Length() << endl;
cout << "位置为:" << a.Locate(2) << endl;
cout << "数值为:" << a.Get(1) << endl;
cout << "删除的数据为:" << a.Delete(1) << endl;
a.PrintList();
//测试插入数据
a.insert(2,0);
a.PrintList();
}