日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++?動態數組模版類Vector實例詳解_C 語言

作者:諾謙 ? 更新時間: 2022-04-28 編程語言

1.實現機制

內部主要通過m_capacity數組容量成員和m_length數組有效長度成員來維護一個T* data數組空間.

內部默認分配一定數量大小的數組指針,每次append尾部追加的時候,無需再次分配空間,直接賦值標志length長度,假如超過當前空間容量,則再次擴大分配新的內存數組,并將舊數組拷貝至新數組及釋放舊數組.

Vector需要實現的public函數如下所示:

  • inline int capacity()?獲取容量
  • inline int length() :?獲取有效長度
  • void resize(int asize) :?改變數組的有效長度
  • void append(const T &t) :?尾部追加一個元素
  • T& operator[] (int i) :?通過[]獲取元素
  • T operator[] (int i) const :?通過[]獲取常量元素
  • void clear() :清空數組中的數據
  • inline bool?isEmpty():?數組是否有數據

resize()函數實現細節:

  • 如果resize長度大于當前容量時 :?則擴大分配新的內存數組,并將舊數組拷貝至新數組及釋放舊數組.
  • 如果resize長度小于當前length時 :?則需要將多余的成員進行釋放,調用析構函數實現.
  • 如果resize長度大于當前length時 :?則需要調用默認構造函數來填充內部數組.

2.代碼實現

#ifndef VECTOR_H
#define VECTOR_H
#include "throw.h"
// throw.h里面定義了一個ThrowException拋異常的宏,如下所示:
//#include 
//using namespace std;
//#define ThrowException(errMsg)  {cout<<__FILE__<<" LINE"<<__LINE__<<": "<
class Vector
{
    T* m_data;
    int m_length;       // 有效數據的長度
    int m_capacity;     // 分配容量的長度
    // 分配
    T* allocate(int size)
    {
        T* arr = new T[size];
        if(arr == NULL) {
            ThrowException( "No memory to create DynamicArray object ...");
        }
        return arr;
    }
    // 重新分配
    void realloc(int capacity)
    {
        T* newData = allocate(capacity);
        for(int i=0; i當前容量時
        if(asize > m_capacity) {
            realloc(asize);
        }
        if (asize < m_length)    // 分配的大小<當前大小時,則調用析構
            destruct(asize, m_length);
        else        // 分配的大小>當前大小時,則調用默認構造
            defaultConstruct(m_length, asize);
        m_length = asize;
    }
    // 尾部追加一個元素
    void append(const T &t)
    {
        if(m_length == m_capacity) {
            realloc(m_capacity+20);     // 如果容量滿了,則默認增加20個容量.方便后面append無需再次分配內存
        }
        m_data[m_length] = t;
        m_length++;
    }
    T& operator[] (int i)
    {
        if((0 <= i) && (i < length()))
        {
            return m_data[i];
        }
        else
        {
            ThrowException("Parameter i is invalid ...");
        }
    }
    T operator[] (int i) const
    {
        return m_data[i];
    }
};
#endif // VECTOR_H

3.測試運行

測試如下所示:

class Test {
public:
    int number;
    Test(int n = 0) {
        number = n;
    }
};
int main(int argc, char *argv[])
{
   Vector arr;
   for(int i = 0; i < 10; i++)
       arr.append(Test(i));
   cout<<"********* Arr Len:"<

運行如下所示:

可以看到我們resize(13)后,由于 resize長度大于當前arr的length,所以則調用默認構造函數來填充內部數組.所以arr[10]至arr[12]的number為0。

總結

原文鏈接:https://blog.csdn.net/qq_37997682/article/details/123111695

欄目分類
最近更新