#include<iostream>
using namespace std;
#include<string>
template <class T>
class Seqlist
{
public:
Seqlist()
:_sz(0)
,_capacity (0)
,_data (NULL)
{ }
~Seqlist ()
{
if(_data != NULL)
{
delete[] _data;
_sz = 0;
_capacity = 0;
}
}
public:
void print();
void CheckCapacity();
void PushBack(const T& d);
void PopBack();
void PushFront(const T& d);
void PopFront();
void ListLen();
void Insert(const int pos,const T& d);
void Del_Insert(const T& d);
int Find(const int pos);
private:
int _sz;
int _capacity;
T* _data;
};
template <class T>
void Seqlist<T>:: print()//想要输出string对象的字符串就“记得要加头文件”
{
int i = 0;
for(i = 0; i<_sz; i++)
{
cout<<_data[i]<<" ";
}
cout<<endl;
}
template <class T>
void Seqlist<T>:: CheckCapacity()
{
if(_sz == _capacity)
{
int newcapacity = _capacity *2+2;
T* tmp = new T[newcapacity];
//memcpy();//当T为自定义类型的时候就会出现浅拷贝的问题
//relloc():和new相比,new在给对象开辟空间的时候会调用构造函数,而relloc不会,有可能使得空间的值变为任意值
int i = 0;
for(i = 0; i< _sz; i++)
{
tmp[i] = _data[i];
}
delete[] _data;
_data = tmp;
_capacity = newcapacity ;
}
}
template <class T>
void Seqlist<T>::PushBack(const T& d)//const string& str :str 为 string 对象,类似于拷贝构造的参数,其参数就是对象
{
CheckCapacity ();
_data[_sz] = d;
_sz++;
}
template <class T>
void Seqlist<T>::PopBack ()
{
_sz--;
}
template <class T>
void Seqlist<T>::PushFront(const T& d)
{
CheckCapacity ();
for(int i = _sz;i>0;i--)
{
_data[i] = _data[i-1];
}
_data[0] = d;
_sz++;
}
template <class T>
void Seqlist<T>::PopFront ()
{
for(int i = 0; i <_sz-1;i++)
{
_data[i] = _data[i+1];
}
_sz--;
}
template <class T>
void Seqlist<T>::ListLen ()
{
cout<<"ListLen: "<<this->_sz <<endl;
}
template <class T>
void Seqlist<T>::Insert(const int pos,const T& d)
{
if(_capacity == 0 )
{
cout<<"_capacity == 0" <<endl;
return ;
}
CheckCapacity ();
for(int i = _sz;i>pos-1;i--)
{
_data[i] = _data[i-1];
}
_data[pos-1] = d;
_sz++;
}
template <class T>
void Seqlist<T>::Del_Insert(const T& d)
{
if(_capacity == 0 )
{
cout<<"_capacity == 0" <<endl;
return ;
}
int i = 0;
while(_data[i] != d)
{
i++;
}
for(int j = i; j < _sz-1;j++)
{
_data[j] = _data[j+1];
}
_sz--;
}
template <class T>
int Seqlist<T>::Find(const int pos)
{
return _data[pos-1];
}
void test() //尾插尾删,插入,删除,查找
{
Seqlist<int> s1;
s1.PushBack (1);
s1.PushBack (2);
s1.PushBack (3);
s1.PushBack (4);
s1.PushBack (5);
s1.PushBack (6);
s1.PushBack (7);
s1.PopBack ();
s1.print ();
s1.Insert (3,6);
s1.print ();
s1.Del_Insert (6);
s1.print ();
int d = s1.Find (1);
cout <<d<<endl;
}
void test1()//自定义类型
{
Seqlist<string> s1;
s1.PushBack ("hello");
s1.PushBack ("hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
s1.PushBack ("world");
s1.Insert (1," change ");
s1.print ();
s1.ListLen ();
}
void test2()//尾插前插前删
{
Seqlist<int> s1;
s1.PushBack (1);
s1.PushBack (2);
s1.PushBack (3);
s1.PushFront (4);
s1.PopFront ();
s1.print ();
s1.ListLen ();
}
int main()
{
test();
cout<<"*************"<<endl;
test1();
cout<<"*************"<<endl;
test2();
cout<<"*************"<<endl;
return 0;
}
用模板实现顺序表
最新推荐文章于 2020-07-28 19:28:41 发布