#调试半天了。实在没办法上所以才来这边求助。
#有大佬帮忙,万分感谢。
#下面是我的代码,我尽量把每个函数的功能都解释了。希望大佬帮帮忙。再次感谢
//
// main.cpp
// arraylist
//
// Created by on 2017/4/9.
// Copyright © 2017年 . All rights reserved.
//
#include <iostream>
#include<sstream>
#include<exception>
#include<algorithm>
using namespace std;
template <class T>
class linearlist{
public:
linearlist(int initialcapacity);//构造函数,开辟initialcapacity个数组空间
//~linearlist();
bool empty();//判断数组是否为空
T& get(int theIndex) const;//返回索引值为theIndex的内容
void erase(int Index);//删除索引为index的元素
void insert(int theIndex,const T& theElement);//在索引为theIndex插入内容为theElement的元素
void output();//输出线性表
void changeLength(T*& a,int oldLength,int newLength);//改变线性表的长度
bool checkIndex(int theIndex) const;//判断索引值theindex在0于listsize-1之间
private:
int arraylength;//线性表长度
T* element;//线性表元素
int listsize;//线性表元素个数
};
template <class T>
void linearlist<T>::output() {
for(int i=0;i<arraylength;i++)
{
cout<<*element[i]<<" ";
}
cout<<endl;
cout<<"arraylength:"<<arraylength<<endl;
cout<<"listsize:"<<listsize<<endl;
}
template <class T>
void linearlist<T>::changeLength(T*& a,int oldLength,int newLength ) {
if(newLength<0)
{
cout<<"newLength cant be 0";
}
else
{
T *temp=new T[newLength];
int number = min(oldLength, newLength);//需要复制的元素的个数
copy(a,a+number,temp);
delete [] a;
a=temp;
}
}
template <class T>
void linearlist<T>::insert(int theIndex,const T& theElement) {
if(theIndex<0||theIndex>arraylength)
cout<<"无效索引";
else
{
if(theIndex==arraylength)
{
changeLength(element, arraylength, arraylength*2);
arraylength=arraylength*2;
}
else if(listsize==0)
{
element[theIndex-1]=theElement;
listsize++;
}
}
}
template <class T>
void linearlist<T>::erase(int Index) {
if(checkIndex(Index));
else
copy(element+Index+1,element+listsize,element+Index);
}
template <class T>
T& linearlist<T>::get(int theIndex) const {
checkIndex(theIndex);
return element[theIndex-1];
}
template <class T>
bool linearlist<T>::checkIndex(int theIndex) const{
if(theIndex<0||theIndex>listsize)
{
ostringstream s;
s<<"error";
return true;
}
return false;
}
template <class T>
linearlist<T>::linearlist(int initialcapacity){
if(initialcapacity<1)
{
ostringstream s;
s<<"数组长度必须大于0";
}
arraylength=initialcapacity;
element=new T[arraylength];
listsize=0;
}
template <class T>
bool linearlist<T>::empty() {
if(listsize>0)//若listsize大于0,则线性表不为空,返回false
return false;
else
return true;
}
int main(int argc, const char * argv[]) {
// insert code here...
linearlist<string> l1(10);//生成线性表,空间为10
l1.output();//输出目前的线性表
l1.insert(0, "f");//在位置0的地方插入f
l1.output();//再次输出目前的线性表
return 0;
}