我们都知道,数组是静态地分配空间放入对应的元素,一旦配置了就不能改变,若要改变其大小,需要进行“配置新空间->数据移动->释还新空间”的过程,成本代价太高。接下来就体现了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;
}