一、前言
最近几天因为要准备考研的专业课,开始研究C++的数据结构,同时阅读了清华大学出版社的《数据结构(C++版)》这本书,在阅读的同时,跟着把书上的代码一起敲了一遍,同时上传上来,供你们参考。作为一个传统的Java选手,初次接触C++,如果其中有什么错误,还望各位海涵,并予以告知。
二、电梯
三、模板类是什么?
根据书上附录所说,“假如一个类包含类型不确定的成员变量,或成员函数的返回类型、形参的类型不能确定,就可以用模板类来解决这个问题”。
此时,我们需要在模板类的上一行添加
template <class Datatype>
以声明使用了DataType这个名字作为实例类的对象。
三、代码
我将顺序表的类模板和实现分别编写在了两个文件内,分别为SeqListImplement.cpp 和 SeqListTemplate.cpp。
SeqListTemplate.cpp
#include <iostream>
using namespace std;
const int MaxSize = 100;
template<class DataType>
class SeqList{
public:
SeqList(){length = 0;}
SeqList(DataType a[],int n);
~SeqList() {};
int Length(){return length;}
DataType Get(int i);
int Locate(DataType x);
void Insert(int i, DataType x);
DataType Delete(int i );
void printList();
private:
DataType data[MaxSize];
int length;
};
template<class DataType>
SeqList<DataType> ::SeqList(DataType a[], int n) {
if (n>MaxSize > n)throw "Error with input";
for (int i=0;i<n;i++)
data[i] = a[i];
length = n;
}
template <class DataType>
DataType SeqList<DataType>::Get(int i) {
if (i<1 || i>length)throw "Error with input";
else return data[i-1];
}
template <class DataType>
int SeqList<DataType> ::Locate(DataType x) {
for (int i = 0; i < length; i++) {
if (data[i] == x)
return i+1;
}
return 0;
}
template <class DataType>
void SeqList<DataType> ::Insert(int i, DataType x) {
for (int j = length; j >= i ; j--) {
data[j] = data[j-1];
}
data[i-1] = x;
length++;
}
template <class DataType>
DataType SeqList<DataType> ::Delete(int i) {
DataType temp = data[i-1];
for (int j = i; j < length-1; j++) {
data[i-1] = data[i];
}
length--;
return temp;
}
template<class DataType>
void SeqList<DataType>::printList() {
for (int i = 0; i < length; i++) {
cout << data[i] << " ";
}
}
SeqListImplement.cpp
#include "SeqListTemplate.cpp"
int main(){
int a[10]={1,3,5,7,9,11,13,15,17,19};
SeqList<int> intList(a,10);
intList.printList();
cout <<"\n" << intList.Length() << "\n";
cout << intList.Get(5) << "\n";
cout << intList.Locate(15) << "\n";
intList.Insert(2,2);
intList.printList();
cout << "\n";
intList.Delete(4);
intList.printList();
cout << "\n";
return 0;
}