STL中vector的實現及面試問題
阿新 • • 發佈:2019-01-22
class Vector
{
public:
typedef T* Iterator;
typedef const T* ConstIterator;
Vector(size_t n = 3)
:_start(new T[n])
, _finish(_start)
, _endofStorage(_start + n)
{}
Vector(const Vector<T>& v)
:_start(new T[v.Size()])
, _finish(0)
, _endofStorage(0)
{
if (TypeTraits<T>::_IsPODType().Get())
{
memcpy(_start, v._start, sizeof(T)*v.Size());
}
else
{
for (size_t i = 0; i<v.Size(); i++)
{
_start[i] = v._start[i];
}
}
_finish = _start + v.Size ();
_endofStorage = _start + v.Size();
}
Vector<T>& operator=(const Vector<T>& v)
{
swap(_start, v._start);
_finish = v._finish;
_endofStorage = v._finish;
return *this;
}
Vector<T>& operator=(Vector<T>& v )
{
swap(_start, v._start);
_finish = v._finish;
_endofStorage = v._endofStorage;
return *this;
}
void PushBack(const T& x)
{
checkStorage();
Insert(End(), x);
}
void PopBack()
{
assert(Size());
--_finish;
}
void Insert(Iterator pos, const T& x)
{
checkStorage();
for (Iterator tmp = End(); tmp != pos; tmp--)
{
*(tmp) = *(tmp - 1);
}
*pos = x;
_finish++;
}
void Erase(Iterator pos)
{
for (Iterator tmp = pos; tmp != End(); tmp++)
{
*tmp = *(tmp + 1);
}
_finish--;
}
Iterator Begin()
{
return _start;
}
Iterator End()
{
return _finish;
}
const T& operator[](size_t pos) const
{
assert(pos<Size());
return _start[pos];
}
size_t Size() const
{
return _finish - _start;
}
size_t Capacity()
{
return _endofStorage - _start;
}
protected:
Iterator _start;
Iterator _finish;
Iterator _endofStorage;
void checkStorage()
{
if (_finish == _endofStorage)
{
size_t size = Size();
size_t capacity = Capacity();
capacity = size * 2;
T *tmp = new T[capacity];
if (_start)
{
for (size_t i = 0; i<Size(); i++)
{
tmp[i] = _start[i];
}
delete[] _start;
}
_start = tmp;
_finish = _start + size;
_endofStorage = _start + capacity;
}
}
};
void test1()
{
Vector<int> v;
v.PushBack(1);
v.PushBack(2);
v.PushBack(3);
v.PushBack(4);
v.PopBack();
Vector<int>::Iterator it;
for (it = v.Begin(); it != v.End(); it++)
{
cout << *it << " ";
}
cout << endl;
/*vector<int> v2(v);
vector<int>::iterator it2;
for(it2=v2.begin();it2!=v2.end();it2++)
{
cout << *it2 << " ";
}
cout<<endl;*/
}
void test2()
{
Vector<int> v;
v.PushBack(1);
v.PushBack(2);
v.PushBack(3);
v.PushBack(4);
v.Insert(v.Begin(), 7);
v.Erase(v.End());
Vector<int>::Iterator it;
for (it = v.Begin(); it != v.End(); it++)
{
cout << *it << " ";
}
cout << endl;
}