简单实现 STL 库中 vector。
template<class T>
class Vector {
private:
void _Erase(T* pos) {
if (pos == NULL)
return;
while (pos + 1 < _finish) {
*pos = *(pos + 1);
++pos;
}
}
void Expand() {
if (_finish < _endofstorage)
return;
size_t new_capacity = 2 * Capacity() + 3;
T* tmp = new T[new_capacity];
size_t size = Size();
for (size_t i = 0; i < size; ++i) {
tmp[i] = _start[i];
}
delete[] _start;
_start = tmp;
_finish = _start + size;
_endofstorage = _start + new_capacity;
}
void _Erase(size_t pos) {
if (pos > Size())
return;
while (pos + 1 < Size()) {
_start[pos] = _start[pos + 1];
++pos;
}
}
public:
Vector()
:_start(NULL)
, _finish(NULL)
, _endofstorage(NULL)
{}
void Erase(T* pos){
if (pos != _finish)
_Erase(pos);
--_finish;
}
void Erase(size_t pos) {
if (pos != Size())
_Erase(pos);
--_finish;
}
bool isEmpty() {
return _start == _finish;
}
void Resize(size_t n, T val = 0) {
T* tmp = new T[n];
delete[] _start;
_finish = _start + n;
_endofstorage = _finish;
for (size_ t i = 0; i < n; ++i) {
_start[i] = val;
}
}
void Reserve(size_t n) {
if (n < Capacity())
return;
T* tmp = new T[n];
size_t size = Size();
for (size_t i = 0; i < Size(); ++i) {
tmp[i] = _start[i];
}
delete[] _start;
_start = tmp;
_finish = _start + size;
_endofstorage = _start + n;
}
void Push_Back(T val) {
if (_finish == _endofstorage)
Expand();
_start[Size()] = val;
++_finish;
}
size_t Size() {
return _finish - _start;
}
size_t Capacity() {
return _endofstorage - _start;
}
T& operator[](size_t pos) {
assert(pos < Size());
return _start[pos];
}
const T& Back() {
return _start[Size() - 1];
}
Vector& operator=(const Vector& v) {
Vector tmp(v);
Swap(_start, tmp._start);
Swap(_finist, tmp._finish);
Swap(_endofstorage, tmp._endofstorage);
return *this;
}
Vector(const Vector& v) {
_start = new T[v.Size()];
_finish = _start + v.Size();
_endofstorage = _start + v.Capacity();
for (size_t i = 0; i < v.Size(); ++i) {
_start[i] = v[i];
}
}
~Vector() {
delete[] _start;
_start = NULL;
_finish = NULL;
_endofstorage = NULL;
}
void Show() {
for (int i = Size() - 1; i >= 0; --i) {
cout << _start[i] << endl;
}
}
private:
T* _start;
T* _finish;
T* _endofstorage;
};
欢迎大家共同讨论,如有错误及时联系作者指出,并改正。谢谢大家!