#include <iostream>
using namespace std;
template <class T>
class SeqList
{
public:
SeqList(int maxSize = 100);
virtual ~SeqList();
int getLength() const {return length;}
bool isEmpty() const { return length == 0;}
int getMaxSize() const {return maxSize; };
int findPosByValue(T t); //根据元素查找
T serach(int pos); //根据位置查找
bool removeElementByPos(int pos); //根据位置删除数据
bool removeElementByValue(T value); //根据值删除数据
SeqList& addElements(T t); //添加数据
bool deleteRepeat(); //删除重复数据
void outputData(); //输出数据
private:
int length; //数组实际长度
int maxSize; //数组最大长度
T* element; //数据元素
};
template <class T>
SeqList<T> :: SeqList(int maxSize)
{
this->maxSize = maxSize;
this->element = new T[this->maxSize];
this->length = 0;
}
template <class T>
SeqList<T> :: ~ SeqList()
{
delete [] this->element;
}
template <class T>
SeqList<T> & SeqList<T> :: addElements(T t)
{
if (this->length != getMaxSize())
{
element[this->length] = t;
this->length++;
}
return *this;
}
template <class T>
int SeqList<T> :: findPosByValue(T t)
{
for (int i = 0; i < this->getLength(); i++)
{
if (t == this->element[i])
{
return i;
}
}
return -1;
}
template <class T>
void SeqList<T> :: outputData()
{
for (int i = 0; i < getLength(); i++)
{
if (i != getLength() - 1)
{
cout << element[i] << "--->";
}
else
{
cout << element[i] << endl;
}
}
}
template <class T>
T SeqList<T> :: serach(int pos)
{
if (pos >= 0 && pos < getLength())
{
return this->element[pos];
}
return -1;
}
template <class T>
bool SeqList<T> :: removeElementByPos(int pos)
{
if (pos >= 0 && pos < this->getLength())
{
for (int i = pos; i < this->getLength() - 1; i++)
{
element[i] = element[i+1];
}
this->length --;
return true;
}
return false;
}
template <class T>
bool SeqList<T> :: deleteRepeat()
{
bool flag = false;
for (int i = 0; i < this->getLength() - 1; i++)
{
T temp = this->element[i];
for (int j = i+1; j < this->getLength(); j++)
{
if (temp == this->element[j])
{
removeElementByPos(j);
flag = true;
}
}
}
return flag;
}
template <class T>
bool SeqList<T> :: removeElementByValue(T value)
{
for (int i = 0; i < this->getLength(); i++)
{
if (value == this->element[i])
{
for (int j = i; j < this->getLength() - 1; j++)
{
this->element[j] = this->element[j+1];
}
this->length --;
return true;
}
}
return false;
}
int main(int argc, char* argv[])
{
SeqList<int> myList(100);
myList.addElements(15).addElements(15).addElements(20).addElements(12).addElements(15).addElements(20);
myList.addElements(30).addElements(15).addElements(30).addElements(12).addElements(15).addElements(40);
cout << "原始数据:" << endl;
myList.outputData();
//cout << myList.findPosByValue(30);
//cout << myList.serach(2);
//myList.removeElementByPos(2);
if (myList.deleteRepeat())
{
cout << "删除重复的元素之后:" << endl;
myList.outputData();
}
else
{
cout << "无重复的元素" << endl;
}
return 0;
}