#pragma once
#include
template
class SeqList
{
public:
SeqList()
:_a(NULL)
,_size(1)
,_capacity(1)
{}
SeqList(T* a, size_t size)
:_a(new T[size])
,_size(size)
,_capacity(size)
{
for (size_t i = 0; i < _size; ++i)
{
_a[i] = a[i];
}
}
//拷贝构造函数常规写法
/*SeqList(const SeqList& s)
:_a(new T[s._size])
,_size(s._size)
,_capacity(s._capacity)
{
for (size_t i = 0; i < _size; ++i)
_a[i] = s._a[i];
}*/
//拷贝构造函数现代写法
SeqList(const SeqList& s)
:_a(NULL)
{
SeqList tmp(s._a, s._size);
swap(_a, tmp._a);
_size = s._size;
_capacity = s._capacity;
}
~SeqList()
{
if (_a)
delete[] _a;
}
//赋值运算符重载常规写法
SeqList& operator=(const SeqList& s)
{
if (this != &s)
{
T* tmp = new T[s._size];
for (size_t i = 0; i < s._size; ++i)
{
tmp[i] = s._a[i];
}
delete[] _a;
_a = tmp;
_size = s._size;
_capacity = s._capacity;
}
return *this;
}
//赋值运算符重载现代写法
/*SeqList& operator=(SeqList s)
{
if (this != &s)
{
swap(_a, s._a);
_size = s._size;
_capacity = s._capacity;
}
return *this;
}*/
public:
void Print()
{
for (size_t i = 0; i < _size; ++i)
{
cout<<_a[i]<<" ";
}
cout< 0);
--_size;
}
void Insert(int pos, const T& x)
{
assert(pos >= 0 && pos <= _size);
_CheckCapacity();
int iIndex = _size;
while (iIndex > pos) //int和size_t比较为什么不行?
{
_a[iIndex] = _a[iIndex-1];
--iIndex;
}
_a[iIndex] = x;
++_size;
}
void Erase(size_t pos)
{
assert(_size > 0 && pos < _size);
size_t index = pos;
while (index < _size-1)
{
_a[index] = _a[index+1];
++index;
}
--_size;
}
int Find(const T& x)
{
for (size_t i = 0; i < _size; ++i)
{
if (_a[i] == x)
{
return i;
}
}
return -1;
}
T& operator[](size_t index)
{
assert(index >= 0 && index < _size);
return _a[index];
}
void Reserve(size_t size) //保留空间,增容到size
{
_capacity = size;
_a = (T*)realloc(_a, _capacity * sizeof(T));
}
void Clear() //不释放空间
{
_size = 0;
}
void Size()
{
return _size;
}
protected:
void _CheckCapacity()
{
if (_size+1 > _capacity)
{
_capacity = _capacity*2;
_a = (T*)realloc(_a, _capacity * sizeof(T));
}
}
protected:
T* _a;
size_t _size;
size_t _capacity;
};
文章名称:C++实现顺序表
本文链接:
http://njwzjz.com/article/jedpdg.html