C++数据结构第17课、StaticList 和 DynamicList

    技术2022-07-10  122

    课程目标 — 完成 StaticList 类的具体实现 — 完成 DynamicList 类的具体实现

    1、StaticList 设计要点

    类模板  使用原生数组作为顺序存储空间  使用模板参数决定数组大小

    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]; public: StaticList() { this->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; } sl[0]*=sl[0]; for(int i = 0; i < sl.length(); i++) { cout << sl[i] << endl; } try { sl[5] = 5; } catch (const Exception& obj) { cout << obj.message() <<endl; cout << obj.location() <<endl; } return 0; }

    2、DynamicList 设计要点

    — 类模板  1、申请连续堆空间作为顺序存储空间  2、动态设置顺序存储空间的大小  3、 保证重置顺序存储空间时的异常安全性 — 函数异常安全的概念  1、不泄露任何资源  2、不允许破坏数据 — 函数异常安全的基本保证  如果异常被抛出,对象内的任何成员仍然能保持有效状态,没有数据的破坏及资源泄漏   DynamicList.h

    #ifndef DYNAMICLIST_H #define DYNAMICLIST_H #include "SeqList.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 != nullptr) { this->m_capacity = capacity; this->m_length = 0; } else { THROW_EXCEPTION(NoEnoughMemoryException,"not memory to creat the object"); } } int capacity()const { return m_capacity; } void resize(int capacity) { if(m_capacity != capacity) { T* array = new T[capacity]; if(array != nullptr) { 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,"not memory to resize the object"); } } } ~DynamicList() { delete[]this->m_array; } }; } #endif // DYNAMICLIST_H

    main.cpp

    #include <iostream> #include "StaticList.h" #include "DynamicList.h" using namespace std; using namespace DTLib; int main() { DynamicList<int> l(5); for(int i = 0; i < l.capacity(); i++) { l.insert(0, i); } for(int i = 0; i < l.length(); i++) { cout << l[i] << endl; } l[0] *= l[0]; for(int i = 0; i < l.length(); i++) { cout << l[i] << endl; } try { l[5] = 5; } catch (Exception& e) { cout << e.message() << endl; cout << e.location() << endl; l.resize(10); } l.insert(5, 50); for(int i = 0; i < l.length(); i++) { cout << l[i] << endl; } return 0; }

    在 DynamicList.h 中第 52 条语句为什么 delete[]temp;这句语句不要放在 47 行那里,主要是怕 析构函数抛出异常 使得后面所有的赋值全部不能完成,这就是函数异常安全的概念。

    小结:

    StaticList 通过模板参数定义顺序存储空间DynamicList 通过动态内存申请定义顺序存储空间DynamicList 支持动态重置顺序存储空间的大小DynamicList 中的 resize() 函数实现需要保证异常安全
    Processed: 0.009, SQL: 9