实验一作业

来源:互联网 发布:windows怎么读音发音 编辑:程序博客网 时间:2024/05/29 16:30
#include<iostream>
using namespace std;
const int MaxSize = 100;
template<class DataType>
class SeqList
{
public:
SeqList() { length = 0; }
SeqList(DataType a[], int n) ;
~SeqList() {};
int Length()
{
return length;
}
DataType Get(int i);
int Locate(DataType x);
void Insert(int i, DataType x);
DataType Delete(int i);
void PrintList();
private:
DataType data[MaxSize];
int  length;


};


template<class DataType>
SeqList<DataType>::SeqList(DataType a[], int n)
{
if (n > MaxSize)
throw "参数非法";
for (int i = 0; i < n; i++)
{
data[i] = a[i];
}
length = n;
}


template<class DataType>
DataType SeqList<DataType>::Get(int i)
{
if (i<1 && i>length)
throw  "查找位置非法";
else return data[i - 1];
}
template<class DataType>
int SeqList<DataType>::Locate(DataType x)
{
for (int i = 0; i < length;i++)

if (data[i] == x)//下标为1的元素等于x,返回其序号i+1
return i + 1;
return  0;

}
template<class DataType>
void  SeqList<DataType>::Insert(int i,DataType x)
{
if (length >= MaxSize)
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++ ;
}
template<class DataType>
DataType SeqList<DataType>::Delete(int i)
{
if (length == 0)
throw "下溢";
if (i<1 || i>length)
throw "删除位置非法";
DataType x = data[i - 1];
for (int j = i; j < length; j++)
data[j - 1] = data[j];
length--;
return x;
}
template<class DataType>
void  SeqList<DataType>::PrintList()
{
for (int i = 0; i < length; i++)
{
cout << data[i]<<endl;
}
}

      int main()
{
int arr[10] = {1,5,44,6,15,70};
SeqList<int> demo( arr, 10);

cout<<"输出所有信息"<<endl;
demo.PrintList();
cout << "删除的信息" << endl;
cout << demo.Delete(3) << endl;
cout << "删除后的信息" << endl;

demo.PrintList();

                  system("pause");

cout << "增加的信息" << endl;
cout << "10" << endl;
demo.Insert(2,10);
cout << "增加后的信息" << endl;
cout <<  demo.Locate(15)<<endl; 
cout << demo.Get(5) << endl;
demo.PrintList();
return 0;

        }


原创粉丝点击