动态数组的实现-c++

      数组实现本身不难。问题是如何实现一个动态的数组。也就是无论是增加元素还是删除元素,数组能够自动扩容或缩小。 

       那么如何实现这一点,关键就在于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);
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值