我在实现顺序表基本算法的时候,我在类中定义一个data[MaxSize],MaxSize=100的数组,然后我在下面的方法里创建了一个动态数组,然后我在调试的时候发现,所有的方法都是在data[MaxSize]上进行的,也就是每个方法里都是在data[100]进行操作的,我想的是在动态数组上进行操作,不知道怎么实现?
#include<iostream>
const int MaxSize = 100;
template<class Type>
class ArrayList {
private:
Type data[MaxSize];
Type* pointer; //指向动态分配的数组
int length;
public:
ArrayList() {
length = 0;
pointer = NULL;
std::cout << "Sequence table established!" << std::endl;
}
void InitList(const int& size); //动态创建顺序表
void CreateList(const Type a[]); //初始化顺序表
int ListLength(int& len) const; //获取顺序表长度
bool ListEmpty() const; //判断是否为空
void DispList() const; //展示线性表
bool DeleteList(const int i, Type& e4); //删除指定位置的元素,并用e3接收
~ArrayList() {
std::cout << "Sequence table destoryed!" << std::endl;
}
};
template<class Type>
void ArrayList<Type>::InitList(const int& size)
{
if (size<0 || size>MaxSize) //Judge whether it is out of bounds;
std::cout << "Invalid Input!" << std::endl;
else {
length = size;
pointer = new Type[size]{ 0 }; //动态建立顺序表并初始化为0
std::cout << "Sequence was established!" << std::endl;
}
}
template<class Type>
void ArrayList<Type>::CreateList(const Type a[])
{
int i;
for (i = 0;i < length;i++)
data[i] = a[i];
std::cout << "顺序表建立完成!" << std::endl;
}
template<class Type>
int ArrayList<Type>::ListLength(int& len) const
{
len = length;
return len;
}
template<class Type>
bool ArrayList<Type>::ListEmpty() const
{
if (length == 0) {
std::cout << "顺序表为空!" << std::endl;
return false;
}
else
{
std::cout << "顺序表非空!" << std::endl;
return true;
}
}
template<class Type>
void ArrayList<Type>::DispList() const {
std::cout << "顺序表:" << std::endl;
for (int i = 0;i < length;i++)
std::cout << data[i] << " " ;
std::cout<<std::endl;
}
template<class Type>
void ArrayList<Type>::DestoryList() const
{
delete[] data;
std::cout << "顺序表销毁成功!" << std::endl;
}
template<class Type>
bool ArrayList<Type>::DeleteList(const int i, Type& e4)
{
int j = i - 1;
if (i<0 || i>length) { //判断是否越界
std::cout << "删除失败!" << std::endl;
return false;
}
else {
for (j;j < length;j++) { //将所有元素前移一位
e4 = data[j];
data[j] = data[j + 1];
}
length--;
std::cout << "删除成功!" << std::endl;
return true;
}
}
int main() {
using std::cin;
using std::cout;
using std::endl;
int ar[] = { 1,2,3,4,6,7,8,9,10 };
ArrayList<int> object;
int e4 = 0;
object.DeleteList(6, e4); //测试DeleteList函数
cout << "被删除的元素值为:" << e4 << endl;
cout << "此时的顺序表长度为:" << object.ListLength(len) << endl;
object.DispList();
return 0;
}