如何自己实现模板类(简单案例——顺序表)

可以将模板类SeqList的定义及成员函数的实现代码全部写到SeqList.h头文件中,则在实例化该类后可进行基本的线性表操作

具体的代码怎么写,其实核心就是 template<class T> 其中 T 就是一个未知的类型,在写头文件时,变量的类型都用T代替。用户在使用此模板时应该把要使用的变量类型填入进去(可以是基本类型 如 int char 等等  也可以是用户自定义的复杂类型 如 结构体、类)

下面是SeqList.h头文件的写法(这里把实现代码也写在了头文件中)

#ifndef SEQLIST_H_INCLUDED
#define SEQLIST_H_INCLUDED

#include <iostream>
using namespace std;
const int MAX = 1005;

template <class T>
class SeqList{
public:
    SeqList(){length = 0;}//无参构造函数
    SeqList(const T a[], int n);//有参构造函数,使用含有n个元素的数组a初始化

    int GetSeqList(){return length;}//获取顺序表的长度
    void PrintSeqList();//按顺序打印表中的元素
    void Insert(int i, T x);//在顺序表的第i个位置插入值为x的新元素
    T Delete(int i);//删除顺序表第i个元素,并返回该元素的值
    T Get(int i);//获取顺序表第i个元素
    int Locate(T x);//查找顺序表中值为x的元素,找到后返回其位置
private:
    T date[MAX];
    int length;
};

template<class T>
SeqList<T>::SeqList(const T a[], int n)
{
    if(n >  MAX)  throw "数组长度超过线性表最大长度" ;
    for(int i = 0; i < n; i++)
        date[i] = a[i];
    length = n;
}

template<class T>
void SeqList<T>::PrintSeqList()
{
    cout << "按序号一次遍历线性表中的各个数据元素:" << endl;
    for(int i = 0; i < length; i++)
        cout << date[i] << " ";//若数据类型为复杂类型,应当对 << 进行重载
    cout << endl;
}

template<class T>
void SeqList<T>::Insert(int i, T x)
{
    if(length >= MAX) throw "上溢异常";
    if(i < 1 || i > length + 1) throw "位置异常";
    for(int j = length; j >= i; j--)
        date[j] = date[j-1];
    date[i-1] = x;
    length++;
}

template<class T>
T SeqList<T>::Delete(int i)
{
    if(length == 0) throw "下溢异常";
    if(i < 1 || i > length) throw "位置异常";
    T x = date[i-1];
    for(int j = i; j < length; j++)
        date[j-1] = date[j];
    length--;
    return x;
}

template<class T>
T SeqList<T>::Get(int i)
{
    if(i < 1 || i > length) throw "查找位置非法";
    return date[i-1];
}

template<class T>
int SeqList<T>::Locate(const T x)
{
    for(int i = 0; i < length; i++)
        if(x == date[i])   return i + 1;
    return 0;//查找失败
}

#endif // SEQLIST_H_INCLUDED

下面是使用该头文件

#include <iostream>
#include "SeqList.h"
using namespace std;

int main()
{
    int a[7] = {1, 2, 3, 4, 5, 6, 7};
    SeqList<int> List(a, 7);
    List.PrintSeqList();
    List.Insert(1, 0);
    List.PrintSeqList();
    int x = List.Delete(8);
    cout << "删除元素:" << x << endl;
    List.PrintSeqList();
    int p = List.Locate(4);
    cout << "元素4的位置:" << p << endl;
    return 0;
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值