我们模拟vector是用迭代器(start,end,endofstorage)来控制增删查改操作的
namespace simulation {
template<class T>//定义模板
class vector {
public:
typedef T* iterator;
typedef const T* const_iterator;
//
private:
iterator _start;
iterator _finish;
iterator _endofstorage;
};
}
vector()
:_start(nullptr)
,_finish(nullptr)
,_endofstorage(nullptr)
{}
template<class InputIterator>
//【first,last)左闭右开区间
vector(InputIterator first, InputIterator last) {
while (first != last) {
push_back(*first);
first++;
}
}
vector(size_t n, const T& val = T()) {
//const T& val = T()调用T的默认构造的缺省参数
resize(n, val);
}
vector(const vector<T>& v) {
_start = new T[v.capacity()];
size_t sz = v.size();
//提前记录下size
for (size_t i = 0; i < sz; i++) {
_start[i] = v._start[i];//实行深拷贝
}
_finish = _start + sz;
_endofstorage = _start + v.capacity();
}
~vector() {
if (_start) {
delete[] _start;
_start = _finish = _endofstorage;
}
}
//我本身是一个const对象,不可变,所以就需要调用一个const函数,
//但我要是一个非const对象,那么调用非const或者const函数是都都可以的
//这 成员函数加个const,这样const和非const对象都就可以调用了
size_t size()const {
return _finish - _start;
}
size_t capacity() const {
return _endofstorage - _start;
}
iterator begin() {
return _start;
}
const_iterator begin()const {
return _start;
}
iterator end() {
return _finish;
}
const_iterator end()const {
return _finish;
}
T& operator[](size_t pos) {
assert(pos < _finish);
return _start[pos];
}
const T& operator[](size_t pos)const {
assert(pos < _finish);
return _start[pos];
}
void reserve(size_t n) {
if (n > capacity()) {
T* tmp = new T[n];
size_t sz = size();
//提前存下size,因为后面start会变动
if (_start) {
for (size_t i = 0; i < sz; i++) {
tmp[i] = _start[i];
}
//这里拷贝原来的数据不用memcpy是因为memcpy是浅拷贝我们vector要的是深拷贝
//所以用for循环调用赋值运算符重载,实现对象的深拷贝
delete[] _start;
}
_start = tmp;
_finish = _start + sz;
_endofstorage = _start + n;
}
}
void resize(size_t n, const T& val = T()) {
//将前n个数据初始化为val
//从当前已有数据后面开始
if (n < size()) {
_finish = _start + n;
}
else {
reserve(n);
while (_finish != _start+n) {
*_finish = val;
_finish++;
}
}
}
void push_back(const T& x) {
if (_finish == _endofstorage) {
//判断是否需要扩容
size_t newcapacity = capacity() == 0 ? 4 : capacity() * 2;
reserve(newcapacity);
}
*_finish = x;
_finish++;
//或者insert(--end());
}
iterator insert(iterator pos, const T& x) {
assert(pos >= _start && pos <= _finish);
if (_finish == _endofstorage) {
size_t len = pos - _start;
//算出pos的相对位置
size_t newcapacity = capacity() == 0 ? 4 : capacity()
reserve(newcapacity);
pos = _start + len;
}
iterator end = _finish - 1;
while (end >= pos) {
*(end + 1) = *end;
--end;
}
*pos = x;
++_finish;
return pos;
}
iterator erase(iterator pos) {
assert(pos >= _start && pos < _finish);
iterator it = pos + 1;
//将pos后面的数据朝前覆盖
while (it != _finish) {
*(it - 1) = *it;
++it;
}
_finish--;
return pos;
}
void swap(vector<T>& v) {
std::swap(_start, v._start);
std::swap(_finish, v._finish);
std::swap(_endofstorage, v._endofstorage);
}
vector& operator=(vector<T> v) {
swap(v);
//创建一个临时对象,临时对象为v的拷贝
//交换this与v的数据,出了作用域以后
//this获得新的数据,临时对象v出作用域销毁
return *this;
}