实现任意类型可扩容数组

本文详细介绍了如何使用C++实现一个自定义的动态数组类,包括初始化、扩容、添加元素、插入元素、删除元素和获取元素等核心功能,并通过一个简单的测试用例展示了其基本用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.头文件array.h

#ifndef array
#define array

template <class T>
class array{
private:
	int length;
	int size;
	T *base;
public:
	bool init();
	bool EnsureFul();
	bool add(T item);
	bool insert(int index, T item);
	T del(int index);
	T getItem(int index);
	void display;
};
#endif

2.源文件array.cpp

#include<iostream>
#include"array.h"
using namespace std;

template<typename T> bool array<T>::init(){
	base = (T*) malloc (10 * sizeof(T));
	if (base == nullptr)
		return false;
	size = 10;
	length = 0;
	return true;
};
template<typename T> bool array<T>::EnsureFull(){
	if (length >= size)
	{
		T* newBase = (T*)realloc(base, sizeof(T)* 10 + size);

		if (newBase == nullptr)
			return false;
		base = newBase;
		size += 10;
		newBase = nullptr;
	}
	return true;
};
template<typename T> bool array<T>::add(T item){
	if (!EnsureFull()){
		return false;
	}
	T *p = base + length;
	*p = item;
	length++;
	return true;
};
template<typename T> bool array<T>::insert(int index, T item){
	if (!EnsureFull()){
		return false;
	}
	if (index < 1 || index > length){
		return false;
	}
	T *p = base + length - 1;
	T *q = base + size - 1;
	while (p <= q)
	{
		*(q + 1) = *q;
		q--;
	}
	*p = item;
	q = nullptr;
	p = nullptr;
	length++;
	return true;
}
template<typename T>T array<T>::del(int index){
	if (index < 1 || index > length){
		return NULL;
	}
	T *q = base + index - 1;
	T item = *q;
	q++;
	T *p = base + length;
	while (q <= p){
		*(q - 1) = *q;
		++q;
	}
	length--;
	return item;
}
template<typename T>T array<T>::getItem(int index){
	if (index<1 || index > length){
		return NULL;
	}
	T *q = base;
	return *(q + index - 1);
}
template<typename T> void array<T>::display()
{
	T *q = base;
	T *p = base + length - 1;
	while (q <= p) {
		cout << *(q++) << " ";
	}
	cout << endl;
}

3.测试

void main()
{
	array<int> *Ay = new array<int>;
	Ay->init();
	Ay->add(4);
	Ay->add(5);
	Ay->add(6);
	Ay->insert(1, 7);
	Ay->insert(2, 8);
	Ay->del(3);
	cout<<Ay->getItem(2);
	Ay->display();
	cout << "hello" << endl;
	system("pause");
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值