数组实现本身不难。问题是如何实现一个动态的数组。也就是无论是增加元素还是删除元素,数组能够自动扩容或缩小。
那么如何实现这一点,关键就在于resize函数。当数组元素数目(即size)等于容量(capacity)时,就resize(2 * capacity),实现扩容。
同理,当数组元素数目十分少的时候(这里我们以size只有 capacity/4 为基准),我们就要缩小空间,减少浪费。那么这时候就当size== capacity / 4时,resize(capacity / 2),但是要注意一种特殊情况,如果size == 0,capacity == 1,那么这样 capacity/2 就是 0了,一个数组容量不可能只是0,所以我们还要保证 capacity / 2 != 0。这些关键点实现后,其他就很简单了。
代码如下。如有错误请指正。
#include<iostream>
#include<cassert>
using namespace std;
template<class T>
class Array
{
private:
T* data;
int size;
int capacity;
void resize(int newcapacity)//重新分配空间
{
T* newdata = new T[newcapacity];
for (int i = 0; i < size; i++)
{
newdata[i] = data[i];
}
data = newdata;
capacity = newcapacity;
newdata = nullptr;
}
public:
Array()//默认初始化构造
{
capacity = 5;
data = new T[capacity];
size = 0;
}
Array(int cab)//重载初始化
{
capacity = cab;
data = new T[capacity];
size = 0;
}
bool isempty()//判断是否为空
{
return size == 0;
}
int get_size()
{
return size;
}
int get_capacity()
{
return capacity;
}
void add(int index, T item)//index下标处添加元素
{
assert(index >= 0 && index <= size);
if (size == capacity) resize(2 * capacity);
for (int i = size - 1; i >= index; --i)
{
data[i + 1] = data[i];
}
data[index] = item;
++size;
}
void add_first(T* item)//头添加
{
add(0, item);
}
void add_last(T* item)//尾添加
{
add(size, item);
}
T get(int index)//获取index处元素
{
assert(index >= 0 && index < size);
return data[index];
}
void set(int index, T item)//修改某处元素
{
assert(index >= 0 && index < size);
data[index] = item;
}
bool contains(T item)//是否包含某个元素
{
for (int i = 0; i < size; i++)
{
if (data[i] == item) return true;
}
return false;
}
int find(T item)//找到目标元素下标
{
for (int i = 0; i < size; i++)
{
if (data[i] == item) return i;
}
return -1;
}
T remove(int index)//删除index位元素
{
assert(index >= 0 && index < size);
T ptn = data[index];
for (int i = index; i < size - 1; i++)
{
data[i] = data[i + 1];
}
--size;
if (size == capacity / 4 && (capacity / 2)) resize(capacity / 2);
return ptn;
}
T remove_first()//删除头元素
{
return remove(0);
}
T remove_last()//删除尾元素
{
return remove(size - 1);
}
void removeElem(T elem)//删除指定元素
{
int index = find(elem);
if (elem != -1) remove(index);
}
}