漫画算法笔记 数组实现

漫画算法笔记

数组实现

#include <iostream>
#include <stdlib.h>
using namespace std;

//C/C++代码实现
template<typename T>
class MyArray
{
public:
	MyArray(int capacity)
		:_capacity(capacity)
		,_size(0)
	{
		_data = new T[capacity]();
	}

	~MyArray()
	{
		delete[] _data;
	}

	T& operator[](int index)
	{
		return _data[index];
	}

	void toString()
	{
		for (int i = 0; i < _size; ++i)
		{
			cout << _data[i] << " ";
		}
		cout << endl;
	}

	/*
		数组插入元素
		@param element 插入的元素
		@param index 插入的位置
	*/
	void insert(const int &element, const int &index)
	{
		//判断访问下标是否超出范围
		if ( index < 0 || index > _size )
		{
			throw out_of_range("超出数组实际元素范围!");
		}

		//如果实际元素达到数组容量上限,则对数组进行扩容
		if (_size >= _capacity)
			resize();

		//将元素右移
		for ( int i = _size - 1; i >= index; --i )
		{
			_data[i + 1] = _data[i];
		}

		//放置元素
		_data[index] = element;
		++_size;
	}

	/*
		数组删除元素
		@param index 删除的位置
	*/
	T remove(int index)
	{
		//判断访问下标是否超出范围
		if (index < 0 || index > _size)
		{
			throw out_of_range("超出数组实际元素范围!");
		}

		T delElement = _data[index];

		//元素左移
		for ( int i = index; i < _size - 1; ++i )
		{
			_data[i] = _data[i + 1];
		}

		--_size;
		return delElement;
	}

private:
	/*
		数组扩容
	*/
	void resize()
	{
		int newCapacity = _capacity * 2;
		T *newData = new T[newCapacity]();
		memcpy(newData, _data, sizeof(T) * _capacity);

		delete[] _data;
		_data = newData;
		_capacity = newCapacity;
	}

	T* _data;
	int _capacity;
	int _size;
};

int main(int argc, char** argv)
{
	auto *arr = new MyArray<int>(4);
	arr->insert(3, 0);
	arr->insert(7, 1);
	arr->insert(9, 2);
	arr->insert(5, 3);
	arr->toString();		//3 7 9 5

	arr->insert(6, 1);
	arr->toString();		//3 6 7 9 5

	arr->remove(1);
	arr->toString();		//3 7 9 5

	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值