C++ 可變數組實現


話不多說,直接上代碼,看注釋

#include <iostream>
#include <cstring>

using namespace std;

// 可變數組實現
template<class T>
class Array {
    template<class E>
    friend ostream& operator<<(ostream &_cout, Array<E> &array);  // 重載  << 運算符可直接實現打印
    int mSize = 0, mCapacity;  // 數組元素個數; 數組容量
    T *mPosition;  // 數組首地址
    int indexCheck(int position){
        if (position > mSize || position < -(mSize)) throw out_of_range("數組越界");  // 輸入參數越界時,拋出異常
        return position < 0 ? position + mSize : position;  // 支持負索引,最后一個索引為-1
    }

    void expandCapacity(){
        mCapacity += 5;
        T *newPosition = new T[mCapacity]; // 每次申請5個
        memcpy(newPosition, mPosition, mSize * sizeof(T)); // 把原數組的數據拷貝進新數組
        mPosition = newPosition;  // 指針指向更新
    }
public:
    // 數組初始化,輸入參數小於0,默認為5的數組
    explicit Array(int capacity = 5) : mCapacity(capacity) {
        mPosition = new T[mCapacity];  // 在堆區申請內存
    }

    // 析構函數
    ~Array() {
        delete[] mPosition;  // 釋放堆區空間
        mPosition = nullptr;
    }

    // 向數組內添加元素
    void add(T value) {
        // 當前元素等於容量
        if (mSize == mCapacity) expandCapacity();  // 擴大容量
        *(mPosition + mSize) = value;  // 向數組中添加元素
        mSize++;
    }

    // 獲取數組內指定索引的元素
    T get(int position) {
        return *(mPosition + indexCheck(position));
    }

    // 重載[]運算符,可以使用索引獲取
    T operator[](int position) {
        return get(position);
    }

    // 獲取當前元素個數
    int size() const {
        return mSize;
    }

    // 刪除數組類指定位置的元素
    bool remove(int position){
        position = indexCheck(position);
        for (int i = position+1; i < mSize; ++i) {
            *(mPosition+i-1) = *(mPosition+i);  // 所有元素前移
        }
        mSize--;
        return true;  // 刪除成功
    }

    bool insert(int position, int value){
        position = indexCheck(position);  // 索引合法性檢查
        if (mSize == mCapacity) expandCapacity();  // 如果當前數組已滿,擴大容量
        for (int i = mSize; i >= position; --i) {
            *(mPosition+i+1) = *(mPosition+i);
        }
        *(mPosition+position) = value;
        mSize ++;
        return true;
    }
};

//  重載  << 運算符可直接實現打印
template <class T>
ostream &operator<<(ostream &_cout, Array<T> &array){
    cout << "[";
    for (int i = 0; i < array.mSize; ++i) {
        cout << array[i];
        if (i != array.mSize-1) cout << ", ";
    }
    cout << "]";
    return _cout;
}

 

如有問題,感謝批評指正


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM