【C++】STL -- Vector容器的用法

我们都知道,数组是静态地分配空间放入对应的元素,一旦配置了就不能改变,若要改变其大小,需要进行“配置新空间->数据移动->释还新空间”的过程,成本代价太高。接下来就体现了vector的优势。
vector功能:实现动态的分配数组,数组元素的大小随着vector对象元素个数变化而变化。
vector的数据结构:线性连续空间,会分配额外的空间以适应可能的增长,这里也体现了容量的观念。

Vector的参数:

 

vector的分配策略:以两个迭代器start和finish分别指向配置得来的连续空间中目前已经被使用的范围。endofstorage指向整块连续(备用空间)的尾端。

Vector的一些操作:

 

 

对于以上的操作以后会补充在里边

 

简单的模拟Vector的实现:

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

typedef int DataType;
class Vector
{
public:

	//构造函数
	Vector()
		: start(NULL)
		, finish(NULL)
		, endofstorage(NULL)
	{}

	~Vector();

	//拷贝构造
	Vector(const Vector& t)
	{
		start = new DataType[t.Size()];
		finish = start + t.Size();
		endofstorage = start + t.Size();

		memcpy(start, t.start, (sizeof(DataType)* t.Size()));
	}

	//元素个数
	size_t Size() const
	{

		return finish - start;
	}

	//赋值运算符重载
	Vector& operator=(Vector t)
	{
		swap(this->start, t.start);
		swap(this->finish, t.finish);
		swap(this->endofstorage, t.endofstorage);

		return *this;
	}

	//容量
	size_t Capacity() const
	{

		return endofstorage - start;
	}

	//扩容
	void Reverse(size_t n)
	{
		if (n > Capacity())
		{
			Expand(n);
		}

	}

	void Expand(size_t n)
	{
		const size_t size = Size();
		const size_t capacity = Capacity();

		DataType* newcapacity = new DataType[n];

		for (size_t i = 0; i < size;i++)
		{
			newcapacity[i] = start[i];

		}

		delete[] start;

		start = newcapacity;
		finish = start + size;
		endofstorage = start + n;
	}

	//尾插
	void PushBack(DataType x)
	{
		if (finish == endofstorage)
		{
			size_t newcapacity = Capacity() > 0 ? Capacity() * 2 : 3;
			Expand(newcapacity);
		}

		*finish = x;
		finish++;
	}

	//尾删
	void PopBack()
	{
		if (finish)
		{
			finish--;
		}

	}

	//头插
	void PushFront(DataType x)
	{
		if (finish == endofstorage)
		{
			size_t newcapacity = Capacity() > 0 ? Capacity() * 2 : 3;
			Expand(newcapacity);
		}


	}

	//打印顺序表
	void PrintVector()
	{
		for (size_t i = 0; i < Size(); i++)
		{
			cout << start[i] << "-->";
			
		}
		cout << endl;
	}
private:

	DataType* start;
	DataType* finish;
	DataType* endofstorage;
};

//析构函数
Vector::~Vector()
{
	if (finish)
	{
		delete[] start;
		start = finish = endofstorage = NULL;
	}
}

int main()
{
	Vector v1;
	v1.PushBack(1);
	v1.PushBack(2);
	v1.PushBack(3);
	v1.PushBack(4);
	v1.PrintVector();
	cout << "size:" << v1.Size() << endl;
	cout << "capacity:"<<v1.Capacity() << endl;

	v1.PopBack();
    v1.PrintVector();


	system("pause");
	return 0;
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值