01数据结构之自定义可扩展数组

仿vector写一个动态扩容数组

#include <iostream>
#include <cmath>
using namespace std;

class OutOfException : public exception
{
};

class Array
{
public:
    int size;
    int maxsize; //capicity,动态扩容
public:
    int *arr;

public:
    Array(int maxSize);
    ~Array();
    int &operator[](int i) const; //取数据
    void push_back(int value);
    void remove(int location);
};

Array::Array(int maxSize)
{
    this->size = 0;
    this->maxsize = maxSize;
    arr = new int[maxSize];
}

Array::~Array()
{
    if (this->arr != nullptr)
    {
        delete[] arr;
        arr = nullptr;
    }
}

int &Array::operator[](int i) const
{
    if (i > size - 1)
    {
        return this->arr[0]; // 抛出异常
    }
    else
    {
        return this->arr[i];
    }
}

void Array::push_back(int value)
{
    if (size >= maxsize)
    {
        //扩容
        int newMaxSize = ceil(maxsize + maxsize / 2);
        int *newArr = new int[newMaxSize];
        for (size_t i = 0; i < size; i++)
        {
            newArr[i] = arr[i]; //复制之前的数据
        }
        delete[] arr;
        arr = nullptr;
        arr = newArr; //地址重新指向newArr
        maxsize = newMaxSize;
    }
    arr[size++] = value;
}

void Array::remove(int location)
{
    if (location > size - 1)
    {
        //抛出异常
    }
    else
    {
        for (size_t i = location; i < size - 1; i++)
        {
            arr[i] = arr[i + 1];//等价
            // arr[i] = arr[i++];
            // *(arr + i) = *(arr +(++i));
        }
        size--;
    }
}

void printArray(Array &arr, int size)
{

    for (size_t i = 0; i < size; i++)
    {
        cout << arr[i] << endl;
    }
}

int main(int argc, char const *argv[])
{
    Array arr(2);
    arr.push_back(1);
    arr.push_back(2);
    arr.push_back(3);
    arr.push_back(4);
    arr.push_back(5);
    arr.push_back(6);
    printArray(arr, arr.size);

    arr.remove(2);
    printArray(arr, arr.size);

    cout << "获取值" << arr[0] << endl;
    system("pause");
    return 0;
}

printArray(arr, arr.size);

cout << "获取值" << arr[0] << endl;
system("pause");
return 0;

}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值