C++线性表的顺序存储结构及实现---通过模板类实现

一、前言

最近几天因为要准备考研的专业课,开始研究C++的数据结构,同时阅读了清华大学出版社的《数据结构(C++版)》这本书,在阅读的同时,跟着把书上的代码一起敲了一遍,同时上传上来,供你们参考。作为一个传统的Java选手,初次接触C++,如果其中有什么错误,还望各位海涵,并予以告知。

二、电梯

C++线性表的链接存储结构(单链表)及实现—通过模板类实现

三、模板类是什么?

根据书上附录所说,“假如一个类包含类型不确定的成员变量,或成员函数的返回类型、形参的类型不能确定,就可以用模板类来解决这个问题”。

此时,我们需要在模板类的上一行添加

template <class Datatype>

以声明使用了DataType这个名字作为实例类的对象。

三、代码

我将顺序表的类模板和实现分别编写在了两个文件内,分别为SeqListImplement.cppSeqListTemplate.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;
}
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值