Bootstrap

(C++)Vector 简单的底层实现

Vector是最常用的一个容器了,常见的几个操作有:

vector<int > a;创建对象

vector<int> a(3);创建对象初始化为3

vector<int> a(2,3)创建对象,初始化为2个3

push_pack()尾部插入

pop_back();返回尾元素

size();返回容量大小

insert()对应位置插入元素

底层代码实现:

#include<stdlib.h>
class Vector
{
private:
	int length;  //vector的长度,元素数量
	int *p;     //元素头指针
public:
	Vector();//不初始化
	Vector(int );  //vector<int> a(5);直接初始化的构造函数
	Vector(int ,int);//vector<int> a(3,4);包含3个重复的元素4
	Vector(Vector&);//重写构造
	int pop_back();//返回尾元素
	void push_back(int );//a.push_back(int)
	void clear();
	void inserts(int,int);//指定地方插入()
	~Vector();
	int  operator [] (const int Pos)  //
	{
		if (this->length == 0) //如果没有元素的话返回-1;
 			return -1;
		if (Pos >= 0 && Pos < length)  
		{
			return p[Pos];
		}
		return -1;

	}
	//Vector operator =(const Vector&that)
	//{
	//	//在类内部开了堆的话,拷贝构造需要重写,避免二次(多次)释放,具体搜:深拷贝,浅拷贝
	//	this->length = that.length;
		//释放原有数据的
	//	if (p)
	//	{
	//		free(p);
	//	}
	//	p = (int*)malloc(sizeof(int) * that.length);
	//	memcpy(p, that.p, that.length);
	//	return *this;
	//}
}*Ptr;
Vector::Vector()   
{
	this->length = 0;
	p = (int*)malloc(sizeof(int));
}
Vector::Vector(int a)
{
	this->length = 1;
	p = (int*)malloc(sizeof(int));
	*p = a;
}
Vector::Vector(int a, int b)
{
	this->length = 3;
	p = (int *)malloc(a*sizeof(int));
	for (int i = 0; i < a; i++)
		p[i] = b;
}
Vector::Vector(Vector& that)
{
	this->length = that.length;
	p = (int*)malloc(sizeof(int)*length);
	memcpy(p, that.p, sizeof(int)*length);

}
void Vector::push_back(int a)
{
	this->length++;
	p = (int*)realloc(p, sizeof(int)*length);
	this->p[length - 1] = a;
}
int Vector::pop_back()
{
	int a = p[length - 1];
	return a;
}
void Vector::clear()
{
	//数据还在内存里面等析构函数删除
	this->length = 0;
}
Vector::~Vector()
{
	if (p)
	{
		free(p);
		length = 0;
	}
}
void Vector::inserts(int a, int b)
{
	//首先扩大地址
	int m ;
	length++;
	p = (int*)realloc(p, sizeof(int)*length);
	for (m = length-2; m > a-1; m--)
	{
		p[m+1] = p[m];
	}
	p[a] = b;
}

迭代器的实现过程不是很清楚,因此没有写入。

;