使用C语言实现顺序表之后,学习了C++后试着用C++实现了顺序表。这其中最大的区别可能就在C++类内的函数,隐含了this指针,传参个数要比C少一个。下面上代码。
头文件
# pragma once
#include<iostream>
#include<assert.h>
using namespace std;
typedef int datatype;
class Seqlist
{
public:
Seqlist(datatype data)
:_size(0)
,_capacity(0)
{
_data = new datatype[3];
_size = 1;
_capacity = 3;
_data[0] = data;
}
~Seqlist()
{
assert(this);
delete[] _data;
}
Seqlist(const Seqlist& Other)
{
if(this == &Other)
return;
_data = new datatype[sizeof(Other._data)];
for(int idx = 0; idx<Other._size; idx++)
_data[idx] = Other._data[idx];
_size = Other._size;
_capacity = Other._capacity;
}
Seqlist& operator =(const Seqlist& Other)
{
CheckFull();
if(this == &Other)
return *this;
delete[] _data;
_data = new datatype[Other._size];
for(int idx = 0; idx<Other._size; idx++)
_data[idx] = Other._data[idx];
_size = Other._size;
_capacity = Other._capacity;
return *this;
}
friend ostream& operator<<(ostream& _cout,const Seqlist &Other)
{
for(int idx = 0; idx<Other._size ;idx++)
_cout<<Other._data[idx]<<" ";
return _cout;
}
void PushBack(datatype num)
{
CheckFull();
_data[_size] = num;
_size++;
}
void PopBack()
{
_size--;
}
void PushFornt(datatype num)
{
CheckFull();
for(int idx = _size-1; idx >= 0; idx--)
_data[idx+1] = _data[idx];
_data[0] = num;
_size++;
}
void PopFront()
{
for(int idx = 0;idx<_size-1;idx++)
_data[idx] = _data[idx+1];
_size--;
}
void InsertFornt(datatype Where,datatype num)
{
CheckFull();
int pos = Find(Where);
if(pos == -1)
return;
if(pos == 0)
PushFornt(num);
for(int idx = _size-1;idx>=pos;idx--)
_data[idx+1] = _data[idx];
_data[pos] = num;
_size++;
}
void Del(datatype Where)
{
int pos = Find(Where);
if(pos == -1)
return;
if(pos == _size-1)
return PopBack();
for(int idx = pos; idx < _size-1;idx++)
_data[idx] = _data[idx+1];
_size--;
}
private:
void CheckFull()
{
if(_size == _capacity)
{
datatype* _tmp = new datatype[_size];
for(int idx = 0;idx<_size;idx++)
_tmp[idx] = _data[idx];
delete[] _data;
_data = new datatype[2*_capacity];
for(int idx = 0;idx<_size;idx++)
_data[idx] = _tmp[idx];
_capacity *= 2;
delete[] _tmp;
cout<<"增容"<<endl;
}
}
datatype Find(datatype num)
{
for(int idx = 0;idx<_size;idx++)
{
if(_data[idx] == num)
return idx;
}
return -1;
}
private:
datatype* _data;
int _size;
int _capacity;
};
测试部分,每次测试便打印一次看看结果,检测函数是否完成相对应的任务。
#include<iostream>
#include<assert.h>
#include"head.h"
using namespace std;
void Test()
{
Seqlist s1(0);
cout<<s1<<endl;
s1.PushBack(1);
cout<<s1<<endl;
s1.PushFornt(3);
cout<<s1<<endl;
s1.InsertFornt(1,2);
cout<<s1<<endl;
s1.Del(10);
cout<<s1<<endl;
s1.PopFront();
cout<<s1<<endl;
}
int main()
{
Test();
return 0;
}
测试结果