动态表的模板是STL库中最常用的数据结构,其代码如下:
template <class T>
class SeqList
{
public:
SeqList()
:_array(new T [3]),
_size(0),
_capacity(3)
{
memset(_array,0,sizeof(T)*3);
}
SeqList(const T &x)
:_array(new T[3]),
_size(1),
_capacity(0)
{
_array[0] = x;
}
SeqList(const SeqList & x)
{
_array = new T[x._size];
memcpy(_array, x._array, sizeof(T)*x._size);
_capacity = x._size;
_size = _capacity;
}
void PushBack(const T & x)
{
_CheckCapacity();
_array[_size++] = x;
}
SeqList & operator = (SeqList l)
{
swap(_array, l._array);
swap(_size, l._size);
swap(_capacity, l._capacity);
return *this;
}
~SeqList()
{
if (_array)
{
delete[] _array;
}
}
private:
void _CheckCapacity()
{
if (_size >= _capacity)
{
_capacity *= 3;
T * tmp = new T [_capacity];
memcpy(tmp, _array, sizeof(T)*_capacity);
delete[] _array;
_array = tmp;
}
}
T *_array;
size_t _size;
size_t _capacity;
};
这里当我们用模板演化成用户自定义类型时会出现什么情况呢?- -。明天告诉你
本文出自 “pawnsir的IT之路” 博客,请务必保留此出处http://10743407.blog.51cto.com/10733407/1752363