仿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;
}