#include <iostream>
using namespace std;
template <class T>
class SeqList
{
public:
SeqList(int maxSize = 100);
virtual ~SeqList();
int getLength() const {return length;}
SeqList & addElements(T t); //添加数据,返回this指针
void outputData(); //输出数据
void removeElementByPos(int pos); //根据位置删除元素
bool removeBySelf(int pos, int number); //从第pos个位置开始删除number个元素(pos从0计算)
private:
int length;
int maxSize;
T* elements;
};
template <class T>
SeqList<T> :: SeqList(int maxSize)
{
this->length = 0;
this->maxSize = maxSize;
this->elements = new T[maxSize];
}
template <class T>
SeqList<T> :: ~SeqList()
{
delete[] elements;
}
template <class T>
SeqList<T> & SeqList<T> :: addElements(T t)
{
if (this->length != maxSize)
{
elements[this->length] = t;
this->length++;
}
return *this;
}
template <class T>
void SeqList<T> :: outputData()
{
for (int i = 0; i < this->getLength(); i++)
{
if (i != this->length - 1)
{
cout << elements[i] << "--->";
}
else
{
cout << elements[i] << endl;
}
}
}
template <class T>
void SeqList<T> :: removeElementByPos(int pos)
{
if (pos >= 0 && pos < this->getLength())
{
for (int i = pos; i < this->getLength() - 1; i++)
{
elements[i] = elements[i+1];
}
this->length --;
}
}
template <class T>
bool SeqList<T> :: removeBySelf(int pos, int number)
{
if (pos < 0 || pos > this->getLength() || pos + number > this->getLength())
{
return false;
}
for (int i = 0; i < number; i++)
{
removeElementByPos(pos);
}
return true;
}
int main(int argc, char* argv[])
{
SeqList<int> seqList(100);
seqList.addElements(12).addElements(15).addElements(17).addElements(15).addElements(35);
seqList.outputData();
cout << "请输入删除元素的开始位置:";
int pos;
cin >> pos;
cout << "请输入删除元素的个数:";
int number;
cin >> number;
if (seqList.removeBySelf(pos, number))
{
cout << "删除元素后:";
seqList.outputData();
}
else
{
cout << "输入数据错误";
}
return 0;
}