C++vector模拟实现
程序员文章站
2022-03-23 13:55:08
...
这段代码依靠_start,_finish和_capicity三个指针来维护vector的线性空间
#include<iostream>
#include<assert.h>
using namespace std;
template<typename T>
class Myvector
{
public:
typedef T Vtype;
typedef Vtype* iterator;
typedef const Vtype* Constiterator;
//构造函数
Myvector():_start(NULL),_finish(NULL),_capicity(NULL){}
~Myvector()
{
if (NULL != _start)
{
delete[]_start;
}
_finish = _capicity = _start;
}
//push_back
void push_back(T element)
{
resize();
*_finish = element;
_finish++;
}
//pop_back
void pop_back()
{
assert(_start != _finish);
_finish--;
}
//size()
size_t size()
{
size_t s = _finish - _start;
return s;
}
//capcity()
size_t capicity()
{
size_t cap = _capicity - _start;
return cap;
}
//begin()
iterator begin()
{
return _start;
}
//end()
iterator end()
{
return _finish;
}
T operator[](int index)
{
assert(_start+index<_finish);
return _start[index];
}
void resize()
{
if (_finish==_capicity)
{
size_t _size = _finish - _start;
size_t cap = 2 * _size + 3;
T* newelement = new T[cap];
for (unsigned int i = 0; i < _size; i++)
{
newelement[i] = _start[i];
}
delete[]_start;
_start = newelement;
//末尾元素地址
_finish = _start + _size;
//容量大小
_capicity = _start + cap;
}
}
private:
iterator _start;
iterator _finish;
iterator _capicity;
};
int main(const int argc,const char*argv[])
{
;
Myvector<int>arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
arr.push_back(4);
arr.push_back(5);
cout << arr.size() << " " << arr.capicity() << endl;
Myvector<int>::iterator it = arr.begin();
while (it != arr.end())
{
cout << *it << " ";
it++;
}
for (int i = 0; i < arr.size(); i++)
arr.pop_back();
}