1. 利用模板类完成顺序表(两天时间,今天至少写出大致框架)
代码
//implement template in sqlist
#include <iostream>
#include <cstring>#define MAXSIZE 100using namespace std;template <typename T>
class Sqlist
{unsigned int len = 0;T *ptr_data=NULL;public:Sqlist():ptr_data(new T [MAXSIZE]){cout << "Sqlist init" <<endl;init();}~Sqlist(){cout << "Sqlist destructor" <<endl;delete[] ptr_data;}int push(T element); // append an element at the endT at(unsigned int index); //get element at index postionint init(); //initilize sqlist};template <typename T>
int Sqlist<T>::init()
{if (NULL == ptr_data) //why ther is a warning?{cout << "ptr_data is NULL" <<endl;return -1;}memset(ptr_data, 0, sizeof(T[MAXSIZE]));return 0;
}template <typename T>
int Sqlist<T>::push(T element)
{//is fullif(len == MAXSIZE){cout << "sqlist is full" <<endl;return -1;}*(ptr_data + len) = element;len++;return 0;
}template <typename T>
T Sqlist<T>::at(unsigned index)
{if(index < 0 || len > MAXSIZE){cout << "index is out of range" <<endl;return NULL; //why ther is a warning?}return *(ptr_data + index);
}int main()
{Sqlist<int> list;for(int i=0; i<10; i++){list.push(i*i);}for(unsigned int i=0; i<10; i++){cout << "list.at(" << i << ")" <<list.at(i) <<endl;}cout << "--The end--" << endl;return 0;
}
运行结果