DynamicList

DynamicList设计要点
——类模板
  申请连续空间作为顺序存储空间
  动态设置顺序存储空间的大小
  保证重置顺序存储空间时的异常安全性

DynamicList设计要点
——函数异常安全的概念
  不泄露任何资源
  不允许破坏数据
——函数异常安全的基本保证
  如果异常被抛出
    对象内的任何成员仍然能保持有效状态
    没有数据的破坏及资源泄露

DynamicList设计要点

template <typename T>
class DynamicList : public SeqList<T>
{
protected:
    int m_capacity;  //顺序存储空间的大小
public:
    DynamicList(int capacity);  //申请空间
    int capacity() const;
    /*重新设置顺序存储空间的大小*/
    void resize(int capacity);
    ~DynamicList(); //归还空间
};

DynamicList.h

#ifndef DYNAMICLIST_H
#define DYNAMICLIST_H

#include "Seqlist.h"
#include "Exception.h"

namespace DTLib
{
template <typename T>
class DynamicList : public SeqList<T>
{
protected:
    int m_capacity;  //顺序存储空间的大小
public:
    DynamicList(int capacity)  //申请空间
    {
        this->m_array = new T[capacity];

        if(this->m_array != NULL)
        {
            this->m_length = 0;
            this->m_capacity = capacity;
        }
        else
        {
            THROW_EXCEPTION(NoEnoughMemoryException,"No memory to create Dynamiclist object...");
        }

    }
    int capacity() const
    {
        return m_capacity;
    }
    /*重新设置顺序存储空间的大小*/
    void resize(int capacity)
    {
        if(m_capacity != capacity)
        {
            T* array = new T[capacity];

            if(array != NULL)
            {
                int length = (this->m_length < capacity ? this->m_length : capacity);


                for(int i=0; i<length; i++)
                {
                    array[i] = this->m_array[i];
                }

                T* temp = this->m_array;
                this->m_array = array;
                this->m_length = length;
                this->m_capacity = capacity;
                delete[] temp;

            }
            else
            {
                THROW_EXCEPTION(NoEnoughMemoryException,"No memory to resize Dynamiclist object...");
            }
        }
    }
    ~DynamicList()  //归还空间
    {
        delete[] this->m_array;
    }
};

}
#endif // DYNAMICLIST_H

main.cpp

#include <iostream>
#include "Dynamiclist.h"

using namespace std;
using namespace DTLib;

int main()
{
    DynamicList<int> sl(5);

    for(int i=0; i<sl.capacity(); i++)
    {
        sl.insert(0,i);  //每次都在线性表的头部进行插入
    }

    for(int i=0; i<sl.length(); i++)
    {
        cout << sl[i] << endl;
    }
    cout << endl;

    sl.resize(6);
    sl.insert(5,50);

    for(int i=0; i<sl.length(); i++)
    {
        cout << sl[i] << endl;
    }

    return 0;
}
原文地址:https://www.cnblogs.com/-glb/p/12051550.html