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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值