Vector内存申请简单模拟

本文详细介绍了模板类Vector的实现过程,包括构造函数、push_back方法、析构函数和reallocate方法的具体实现。此外,还展示了如何使用Vector类进行元素的添加,并通过一个示例程序进行了演示。

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

#include
#include
#include

using namespace std;
using std::cout;
using std::cin;

template
class Vector{
public:
Vector():elements(0),first_free(0),my_end(0)
{
elements = alloc.allocate(16);
first_free = elements;
my_end = elements +16;
}
void push_back(const T& t)
{
if(first_free == my_end)
{
reallocate();
}
alloc.construct(first_free,t);
++first_free;
}
~Vector()
{
for(T *p = first_free; p != elements; )
{
alloc.destroy(–p);
}

	if(elements)
	{
		alloc.deallocate(elements, my_end - elements );
	}
}

private:
allocator alloc;
void reallocate()
{
std::ptrdiff_t size = first_free - elements;
std::ptrdiff_t newcapacity = 2*max(size,1);

	T* newelements = alloc.allocate(newcapacity);

	uninitialized_copy(elements,first_free,newelements);

	for(T *p = first_free; p != elements; )
	{
		alloc.destroy(--p);
	}

	if(elements)
	{
		alloc.deallocate(elements, my_end - elements );
	}

	elements = newelements;
	first_free = elements + size;
	my_end = elements + newcapacity;
}
T* elements;
T* first_free;
T* my_end;

};

class A
{
public:
int arry[16];
};

int main()
{
Vector vector0;

int a = 5;
vector0.push_back(a);

int cin_1;
cin>>cin_1;
return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值