表——Vector实现 :
O(1)索引、插入、删除代价高O(N) ( 最后位置除外O(1) )、查找低效;
Vector需要内存指针(Object *)和大小(theSize);
(注:大小不同于容量,size<=capacity,为了节约容量扩展的代价,每次扩展就要变为原来容量的2倍大)
个人根据书中的框架实现,注意到如下问题:
·需要在单参数构造函数Vector(int initSize=0){}中对于初始大小的元素,初始化为0:
for (int i = 0; i < theSize; ++i)
newArray[i] = move(objects[i]);
·在扩容函数void reserve(int newCapacity) {}中当在代码:
for (int i = 0; i < theSize; ++i)
newArray[i] = move(objects[i]);
即使是右值移动完仍然存在;
·对于添加右值元素的函数void push_back(Object && x) {},即使没有它,传统的void push_back(const Object & x)也能完成;
·这里的迭代器,是模拟指针操作实现的,即Object *;(注:如果想要其拥有更丰富的功能,比如对错误的检测,可以参考List的内嵌类类型)
贴上代码,看起来一目了然的,闭上眼睛还能浮现么~
/*
vector
·iterator 为 Object *,功能不丰富
包含:begin()|end()
·vector 需要内存指针和大小
包含:五大函数(其中operator = 为深层拷贝)
resize()|reserve()
operator[]
size()|empty()|clear()|back()|pop_back()|push_back()
*/
template
class Vector
{
public:
explicit Vector(int initSize = 0) :theSize{ initSize },
theCapacity{ initSize + SPARE_CAPACITY } {
objects = new Object[theCapacity];
for (int i = 0; i < theSize; ++i)
objects[i] = 0;
}
Vector(const Vector & rhs) :thsSize{ rhs.theSize },
theCapacity{ rhs.theCapacity }, objects{ nullptr } {
objects = new Object[theCapacity];
for (int i = 0; i < theSize; ++i)
objects[i] = rhs.objects[i];
}
Vector(Vector && rhs) :thsSize{ rhs.theSize },
theCapacity{ rhs.theCapacity }, objects{ rhs.objects } {
rhs.objects = nullptr;
rhs.theSize = 0;
rhs.theCapacity = 0;
}
Vector & operator = (const Vector & rhs) {//拷贝复制
Vector * copy = rhs;
swap(*this, copy);
return *this;
}
Vector operator = (Vector && rhs) {//三步交换
swap(theSize, rhs.theSize);
swap(theCapacity, rhs.theCapacity);
swap(objects, rhs.objects);
}
~Vector() {
delete[] objects;
}
void reserve(int newCapacity) {
if (newCapacity < theCapacity)
return;
Object * newArray = new Object[newCapacity];
for (int i = 0; i < theSize; ++i)
newArray[i] = move(objects[i]);
//右值移动完仍存在
//for (int i = 0; i < theSize; ++i)
// cout << objects[i];
theCapacity = newCapacity;
swap(objects, newArray);
delete []newArray;
}
void resize(int newSize) {
if (newSize > theCapacity)
reservZe(newSize * 2 + 1);
theSize = newSize;
}
bool empty() const {
return size() == 0;
}
int size() const {
return theSize;
}
int capacity() const {
return theCapacity;
}
Object & operator[](int index) {
return object[index];
}
const Object & operator[](int index) const {
return object[index];
}
void clear() {
while (!empty())
pop_back();
}
void pop_back() {
--theSize;
}
void push_back(const Object & x) {
if (theSize == theCapacity)
reserve(2 * theCapacity + 1);
objects[theSize++] = x;
}
void push_back(Object && x) {
if (theSize == theCapacity)
reserve(2 * theCapacity + 1);
objects[theSize++] = move(x);
}
typedef Object* iterator;
typedef const Object* const_iterator;
iterator begin() {
return &objects[0];
}
iterator end() {
return &objects[size()];
}
const_iterator begin() const{
return &objects[0];
}
const_iterator end() const{
return &objects[size()];
}
static const int SPARE_CAPACITY = 16;
private:
int theSize;
int theCapacity;
Object * objects;
};