当前位置: 首页 > >

STL-模拟实现vector(含类型萃取)

发布时间:

1.类型萃取



//类型萃取

struct TrueType
{
bool Get()
{
return true;
}
};

struct FalseType
{
bool Get()
{
return false;
}
};

template
struct Type
{
typedef FalseType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template<>
struct Type
{
typedef TrueType NowType;
};

template
struct Type
{
typedef TrueType NowType;
};






2.主要代码


#include
#include
#include
#include "TypeTrais.h"

using namespace std;

template
class Vector
{
public:
typedef T* Iterator;
typedef const T* ConstIterator;
public:
Vector()
: _start(NULL)
, _finish(NULL)
, _endOfStorage(NULL)
{}

Vector(const Vector& v)
{
_start = new T[v.Capacity()];
//类型萃取

if (Type::NowType().Get())
{
memcpy(_start, v._start, v.Size()*sizeof(T));
}
else
{
for (size_t i = 0; i < v.Size(); ++i)
{
_start[i] = v._start[i];
}
}
_finish = _start + v.Size();
_endOfStorage = _start + v.Capacity();
}

Vector& operator=(const Vector& v)
{
if (this != &v)
{
T* tmp = new T[v.Capacity()];

//类型萃取

if (Type::NowType().Get())
{
memcpy(tmp, v._start, v.Size()*sizeof(T));
}
else
{
for (size_t i = 0; i < v.Size(); ++i)
{
tmp[i] = v._start[i];
}
}

delete[] _start;
_start = tmp;
_finish = _start + v.Size();
_endOfStorage = _start + v.Capacity();

}
return *this;
}

~Vector()
{
delete[] _start;
_start = NULL;
_finish = NULL;
_endOfStorage = NULL;
}

void PushBack(const T& x)
{
CheckCapacity();
*_finish = x;
_finish++;
}

Iterator Insert(Iterator Pos, const T& x)
{
assert(Pos);

CheckCapacity();
size_t size = Pos - _start;
for (size_t i = Size(); i>size; --i)
{
_start[i] = _start[i-1];
}
*Pos = x;
_finish++;

return Pos;
}

Iterator Erase(Iterator Pos)
{
assert(Pos >= _start&& Pos <= _finish);

size_t size = Pos - _start;
for (size_t i = size; i {
_start[i] = _start[i + 1];
}

_finish--;
return Pos;
}

void PopBack()
{
assert(!Empty());
_finish--;
}

T& operator[](size_t index)
{
assert(index < Size());

return _start[index];
}

size_t Size()const
{
return _finish - _start;
}

size_t Capacity()const
{
return _endOfStorage - _start;
}

bool Empty()
{
return !Size();
}

Iterator Begin()
{
return _start;
}

Iterator End()
{
return _finish;
}

ConstIterator Begin()const
{
return _start;
}

ConstIterator End()const
{
return _finish;
}
protected:
T* _start;
T* _finish;
T* _endOfStorage;

private:
void CheckCapacity()
{
if (_finish == _endOfStorage)
{
size_t size = Size();
size_t capacity = Capacity();
T* tmp = new T[capacity * 2 + 3];

if (_start)
{
for (size_t i = 0; i < size; ++i)
{
tmp[i] = _start[i];
}

delete[] _start;
}

_start = tmp;
_finish = _start + size;
_endOfStorage = _start + capacity*2+3;
}
}

};






??



友情链接: