您的位置:首页 > 其它

顺序表Test1

2017-09-17 09:38 197 查看
//ArrayList.h文件

const int MaxSize = 50;

template<class T>   //定义模板类ArrayList

class ArrayList

{

public:
ArrayList() { length = 0 }; //无参构造函数

ArrayList(T a[], int n);  //有参构造函数
~ArrayList() {};
void PrintList();
bool InsertList(int i, T a);
bool DeleteList(int i, T *a);
int Length();
int GetList(T x);
T GetNum(int i);

private:
int length; //线性表的长度
T data[MaxSize]; //存放线性表的数组

};

//ArrayList.cpp文件

#include"ArrayList.h"

template<class T>

ArrayList<T>::ArrayList(T a[], int n)

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

}

template<class T>

bool ArrayList<T>::DeleteList(int i, T *x)

{
if (i>length || i<1)
throw("参数非法");
else
{
*x = data[i - 1];
for (int j = i; j < length; j++)
{
data[j - 1] = data[j];
}
length--;
return true;
}

}

template<class T>

int ArrayList<T>::GetList(T a)

{
for (int i = 0; i < length; i++)
{
if (a == data[i])
{
return i + 1;
}
}
return -1;

}

template<class T>

T ArrayList<T>::GetNum(int x)

{
if (x > length || x < 1)
{
throw "查找位置非法";
}
else
return data[x - 1];

}

template<class T>

bool ArrayList<T>::InsertList(int i, T a)

{
if (i > length + 1 || i < 1)
{
throw("参数错误");
}
else
{
for (int j = length; j >= i; j--)
{
data[j] = data[j - 1];
}
data[i - 1] = a;
length++;
}

}

template<class T>

int ArrayList<T>::Length()

{
return length;

}

template<class T>

void ArrayList<T>::PrintList()

{
for (int i = 0; i < length; i++)
{
cout << data[i] << endl;
}

}

//源.cpp文件

#include<iostream>

#include<string>

using namespace std;

#include"ArrayList.cpp"

int main(void)

{
string a[5] = {"大明","二明","三明","四明","五明"};
ArrayList<string> x(a,5);
cout << "分别是:" << endl;
x.PrintList();
cout <<"总共人数:"<< x.Length() << endl;
cout<<"小明的位置是:"<<x.GetList("小明")<<endl;
cout<<"第三个位置的学生是:"<<x.GetNum(3)<<endl;
x.InsertList(6, "小明");
cout << "插入操作:" << endl;
x.PrintList();
string b;
x.DeleteList(2,&b);
cout << "删除操作:" <<"(删除的学生姓名是"<<b<<")"<< endl;
x.PrintList();
x.~ArrayList();
system("pause");
return 0;

}

运行结果如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: