• StaticList


    到目前为止,我们还无法创建一个顺序存储结构线性表的对象出来,为什么呢?
    顺序存储空间究竟是什么,顺序存储空间的大小是多少?

    StaticList设计要点
    ——类模板
      使用原生数组作为顺序存储空间
      使用模板参数决定数组大小

    template <typename T, int N>
    class StaticList: public SeqList<T>
    {
    protected:
        T m_space[N]; //顺序存储空间,N为模板参数
    public:
        StaticList(); //指定父类成员的具体值
        int capacity() const; 
    };

    StaticList.h

    #ifndef STATICLIST_H
    #define STATICLIST_H
    
    #include "seqlist.h"
    
    namespace DTLib
    {
    template <typename T, int N>
    class StaticList: public SeqList<T>
    {
    protected:
        T m_space[N]; //顺序存储空间,N为模板参数
    public:
        StaticList() //指定父类成员的具体值
        {
            this->m_array = m_space;  //将父类的m_array这个指针指向子类的m_space这个数组
            this->m_length = 0;
        }
        int capacity() const
        {
            return N;
        }
    };
    }
    #endif // STATICLIST_H

    测试main.cpp

    #include <iostream>
    #include "Staticlist.h"
    
    using namespace std;
    using namespace DTLib;
    
    
    
    int main()
    {
        StaticList<int, 5> sl;
    
        for(int i=0; i<sl.capacity(); i++)
        {
            sl.insert(0,i);  //每次都在线性表的头部进行插入
        }
    
        for(int i=0; i<sl.length(); i++)
        {
            cout << sl[i] << endl;
        }
    
        return 0;
    }

     实验二:

    #include <iostream>
    #include "Staticlist.h"
    
    using namespace std;
    using namespace DTLib;
    
    
    
    int main()
    {
        StaticList<int, 5> sl;
    
        for(int i=0; i<sl.capacity(); i++)
        {
            sl.insert(0,i);  //每次都在线性表的头部进行插入
        }
    
        for(int i=0; i<sl.length(); i++)
        {
            cout << sl[i] << endl;
        }
    
        sl[5] = 10;
    
        return 0;
    }

     这个地方抛出了一个异常,因为我们在重载数组操作符时,已经指定了当越界时,就抛出IndexOutOfBoundsException这个类的异常信息。从这个地方,就可以看出抛出异常的好处了,当程序崩溃时,可以让我们快速的定位,如果不在重载数组操作符那个函数中抛出异常,我们将很难定位这种程序崩溃问题。

  • 相关阅读:
    Leetcode 589. N-ary Tree Preorder Traversal
    Leetcode 912. Sort an Array
    Leetcode 1020. Number of Enclaves
    Leetcode 496. Next Greater Element I
    Leetcode 1019. Next Greater Node In Linked List
    Leetcode 503. Next Greater Element II
    Leetcode 1018. Binary Prefix Divisible By 5
    龟兔赛跑算法详解
    Leetcode 142. Linked List Cycle II
    Leetcode 141. Linked List Cycle
  • 原文地址:https://www.cnblogs.com/-glb/p/12046709.html
Copyright © 2020-2023  润新知