SeqList.h
#ifndef __SEQLIST_H__
#define __SEQLIST_H__
template<class T>
class SeqList
{
public:
SeqList();
SeqList(T *_data, int _length);
virtual ~SeqList();
public:
int getLength();
void Insert(int _pos, T _data);
T Delete(int _pos);
void setElement(int _pos, T _data);
T getValue(int _pos);
int getLocation(T _data);
void Traverse();
private:
static const int MaxSize = 100;
T data[MaxSize];
int length;
};
#endif // !__SEQLIST_H__
SeqList.cpp
#include <iostream>
#include "SeqList.h"
using namespace std;
/* Constructor && Distructor */
template <class T>
SeqList<T>::SeqList()
{
length = 0;
}
template <class T>
SeqList<T>::SeqList(T *_data, int _length)
{
if (_length > MaxSize || _length < 0)
throw "Illegal Length";
else
{
length = _length;
for (int i = 0; i < length; i++)
data[i] = *(_data + i);
}
}
template <class T>
SeqList<T>::~SeqList()
{
}
/* Operating Function */
template <class T>
int SeqList<T>::getLength()
{
return length;
}
template <class T>
void SeqList<T>::Insert(int _pos, T _data)
{
if (_pos > length || _pos < 0)
throw "Illegal Posistion";
for (int i = length; i >= _pos; i--)
data[i] = data[i - 1];
data[_pos - 1] = _data;
length += 1;
}
template <class T>
T SeqList<T>::Delete(int _pos)
{
T tempData = data[_pos];
if (_pos > length || _pos <= 0)
throw "Illegal Posistion";
for (int i = _pos - 1; i < length - 1; i++)
data[i] = data[i + 1];
length -= 1;
return tempData;
}
template <class T>
void SeqList<T>::setElement(int _pos, T _data)
{
if (_pos > length || _pos < 0)
throw "Illegal Posistion";
data[_pos - 1] = _data;
}
template <class T>
T SeqList<T>::getValue(int _pos)
{
if (_pos > length || _pos < 0)
throw "Illegal Posistion";
else
return data[_pos - 1];
}
template <class T>
int SeqList<T>::getLocation(T _data)
{
for (int i = 0; i < length; i++)
if (data[i] == _data)
return i + 1;
}
template <class T>
void SeqList<T>::Traverse()
{
for (int i = 0; i < length; i++)
cout << data[i] << " ";
cout << endl;
}
Sequential.cpp
#include <iostream>
#include "SeqList.h"
#include "SeqList.cpp"
using namespace std;
int main()
{
int arr[5] = { 0, 0, 0, 0, 0 };
SeqList<int> list(arr, 5);
list.Traverse();
list.Insert(1, 1);
list.Traverse();
list.Delete(1);
list.Traverse();
list.setElement(2, 2);
list.Traverse();
cout << list.getValue(2) << endl;
cout << list.getLocation(2) << endl;
cout << list.getLength() << endl;
return 0;
}
输出结果:
0 0 0 0 0
1 0 0 0 0 0
0 0 0 0 0
0 2 0 0 0
2
2
5