#include<iostream>
using namespace std;
template <class T>
class List
{
public:
List(int MaxSize = 10);
virtual~List(){ delete[] element; }
bool IsEmpty() const { return(length == 0); }
int Length() const { return length; } //const表示返回值不能被修改。
bool Find(int k, T & x) const; //返回第k个元素保存至x中; &x 是引用传值。
int Search(const T & x) const; //为避免实参被修改,就用const修饰,更安全。
List<T>& Insert(int k, const T & x);
List<T>& Delete(int k, T & x);
int size() const { return MaxSize; }
void show();
void output(ostream& out); //这里定义了一个成员函数,避免使用友元函数进行重载<<。
private:
int length;
int MaxSize;
T *element; // 一维动态数组
};
template <class T>
List<T>::List(int size){
MaxSize = size;
element = new T[MaxSize];
length = 0;
}
template <class T>
bool List<T>::Find(int k, T & x) const{
if (k<0 || k>length - 1) return false;
x = element[k]; return true;
}
template <class T>
int List<T>::Search(const T & x) const{
for (int i = 0; i < length; i++)
if (x == element[i]) return i;
return 0;
}
template <class T>
List<T>& List<T>::Insert(int k, const T & x){
if (k<0 || k>MaxSize - 1) cout << "The position is wrong!" << endl;
else if (length == MaxSize) cout << "beyond the MaxSize!" << endl;
else{
for (int i = length; i > k; i--){
element[i - 1] = element[i];
}
element[k] = x;
length++;
}
return *this;
}
template <class T>
List<T>& List<T>::Delete(int k, T & x){
if (Find(k, x)){
for (int i = k; i < length - 1; i++)
element[i] = element[i + 1];
length--;
}
return *this;
}
template <class T>
void List<T>::show(){
for (int i = 0; i < length; i++){
cout << element[i] << " ";
}
cout<< endl;
}
template <class T>
void List<T>::output(ostream& out){
for (int i = 0; i < length; i++){
out << element[i] << " ";
}
}
template <class T>
ostream & operator<<(ostream& out, List<T>& x){
x.output(out);
return out;
}
void main(){
List<int> MyList(5);
cout << "MaxSize: " << MyList.size() << endl;
cout << "IsEmpty: " << MyList.IsEmpty() << endl;
cout << "Length: " << MyList.Length() << endl;
MyList.Insert(0, 1).Insert(1, 2).Insert(2, 3).Insert(3, 4);
cout << "MyList is: "; MyList.show(); cout << endl;
int z;
MyList.Find(1,z);
cout << "The element in the position of 1 is : " << z << endl;
cout << "The element 4 is in the position of : " << MyList.Search(4) << endl;
MyList.Delete(3, z);
cout << "The delete element is: " << z << endl;
cout << "MyList is: " << MyList << endl;
cout << "Length: " << MyList.Length() << endl;
system("pause");
}