讲到STL库,避免不了容器,此处自定义实现一个vector,命令为myVector。当然,myVector不可与vector相比,大体的功能是实现了,最主要是没有涉及迭代器。
实现的成员函数有:
1、默认构造函数
2、自定义构造函数
3、拷贝构造函数
4、赋值构造函数
5、析构函数
6、下标运算符
7、size()
8、capacity()
9、clear()
10、push_back(t)
11、push_front(t)
12、insert_back(pos,t);
13、insert_before(pos,t);
14、erase(pos);
具体实现代码如下所示:
#include<algorithm>
#include<iostream>
#include<assert.h>
using namespace std;
#define WALK_LENGTH 64 //每次增加空间的长度
template<class T>
class myVector {
private:
T* array;
unsigned int theSize;
unsigned int theCapacity;
T* allocate(unsigned int size) {
return new T[size];
}
void deallocate(T* array) {
if (array)
delete[] array;
}
public:
myVector():array(nullptr),theSize(0),theCapacity(0){}
myVector(unsigned int n, const T& t) :array(nullptr), theSize(0), theCapacity(0) {
while (n--) {
push_back(t);
}
}
//copy constructor
myVector(const myVector<T>& other):array(nullptr),theSize(0),theCapacity(0) {
/*
array = other.array;//array、theSize、theCapacity是私有成员,不允话如此访问
theSize = other.theSize;
theCapacity = other.theCapacity;
*/
*this = other;//此处利用了赋值运算符
}
//operator=
myVector& operator=(const myVector<T>& other) {
if (this == &other)
return *this;
clear();
theSize = other.size();
theCapacity = other.capacity();
array = new T[theCapacity];//申请内存空间
for (unsigned int i = 0; i < theSize; ++i) {
array[i] = other[i];
}
return *this;
}
//destructor
~myVector() {
clear();
}
//[]运算符
T& operator[](unsigned int pos) {
assert(pos < thesize);//防止数据的下标越界
return array[pos];
}
//element theSize
size_t size() {
return theSize;
}
//alloc capacity
size_t capacity() {
return theCapacity;
}
//is empty
bool empty() {
return theSize == 0;
}
//release dynamic memory
void clear() {
deallocator(array);//释放内存
array = nullptr;
theSize = 0;
theCapacity = 0;
}
//add an element in the back of myVector
void push_back(const T& t) {
insert_after(theSize - 1, t);
}
//add an element in the front of myVector
void push_front(const T& t) {
insert_before(0, t);
}
//insert an element after the pos
//the pos must be in [0,theSize)
void insert_after(int pos, const T& t) {
insert_before(pos + 1, t);
}
//insert an element before the pos
//the pos must be in [0,theSize)
void insert_before(int pos, const T& t) {//此成员函数写起来有点挑战性
if (theSize == theCapacity) {
T* oldarray = array;
theCapacity += WALK_LENGTH;//增加容量
array = new T[theCapacity];//申请内存空间
//将数据进行整体搬移
for (int i = 0; i < theSize; ++i)
array[i] = oldarray[i];
deallocate(array);//释放原有的内存空间
}
for (int i = ++theSize; i > pos; --i)
array[i] = array[i - 1];
array[pos] = t;
}
//erases an element in the pos
//pos must be in [0,theSize)
void erase(unsigned int pos) {
if (pos < theSize) {
for (int i = pos + 1; i < theSize; ++i) {
array[i - 1] = array[i];
}
--theSize;
}
}
};
参考文章:《后台开发核心技术与应用实践》——徐晓鑫