C++ Vector 顺序表

本文深入探讨C++中的Vector容器,介绍其作为顺序表的数据结构特性,包括动态内存管理、元素插入与删除、迭代器操作等核心概念,并通过示例代码`Vector.h`和`test.cpp`进行实战演示。
摘要由CSDN通过智能技术生成

Vector.h

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

typedef int DataType;

class Vector
{
public:
	Vector()//构造函数
		: first(NULL)
		, finish(NULL)
		, end(NULL)
	{}

	size_t size() const//当前已用容量
	{
		return finish - first;
	}

	size_t capacity() const//最大容量
	{
		return end - first;
	}

	void reverse(size_t n)//预留空间
	{
		if (n > capacity())
		{
			expand(n);
		}
	}

	void resize(size_t n, DataType value)//设置分配空间,并对多开空间赋值
	{
		if (n < size())//缩小
		{
			finish = first + n;
		}
		else
		{
			if (n > capacity())
			{
				expand(n);//扩容

			}
			size_t index = n - size();
			while (--index)
			{
				*finish = value;
				finish++;
			}

		}
	}


	Vector(const Vector& v)//拷贝构造   v1(v2)
						   //为避免浅拷贝,需用深拷贝另开空间
	{
		DataType *tmp = new DataType[v.size()];
		first = tmp;
		finish = first + v.size();
		end = first + v.size();
		memcpy(first, v.first, sizeof(DataType)*v.size());
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值