使用C++手动封装一个顺序表,包含成员数组一个,成员变量N个
#include <iostream>
using namespace std;
using datatype=int;
#define MAX 30
struct SqList
{
private:
//存放数据元素
datatype *data;
int len;//顺序表实际长度
int size;//元素大小
public:
//初始化函数
void init(int s)
{
size = s; //当前数组的最大容量
len = 0;
data = new datatype[size]; //在堆区申请一个顺序表容器
}
//要实现的函数
//判空函数
bool empty();
//判满函数
bool full();
//添加数据函数
bool add(datatype e);
//求当前顺序表的实际长度
int length();
//任意位置插入函数
bool insert_pos(int pos, datatype e);
//任意位置函数函数
bool delete_pos(int pos);
//访问容器中任意一个元素 at
datatype at(int index);
//君子函数:二倍扩容
void expend();
//展示
void show();
};
//判空函数
bool SqList::empty()
{
return len==0;
}
//判满函数
bool SqList::full()
{
return size==len;
}
//添加数据函数
bool SqList::add(datatype e)
{
if(full())
{
expend();
}
data[len]=e;
len++;
return 1;
}
//求当前顺序表的实际长度
int SqList::length()
{
return len;
}
//任意位置插入函数
bool SqList::insert_pos(int pos, datatype e)
{
if(full())
{
expend();
}
if(pos<0||pos>len)
{
cout<<"插入失败"<<endl;
return 0;
}
for(int i=len;i>pos-1;i--)
{
data[i]=data[i-1];
}
data[pos-1]=e;
len++;
return 1;
}
//任意位置删除函数
bool SqList::delete_pos(int pos)
{
if(pos<0||pos>len||empty())
{
cout<<"删除失败"<<endl;
}
for(int i=pos-1;i<len-1;i++)
{
data[i]=data[i+1];
}
len--;
return 0;
}
//访问容器中任意一个元素 at
datatype SqList::at(int index)
{
return data[index-1];
}
//君子函数:二倍扩容
void SqList::expend()
{
int* new_data=new datatype[size*2];
for(int i=0;i<len;i++)
{
new_data[i]=data[i];
}
delete data;
data=new_data;
}
void SqList::show()
{
for(int i=0;i<len;i++)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
int main()
{
SqList list;
list.init(1);
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
list.add(7);
list.add(8);
list.add(9);
list.add(10);
list.add(11);
list.add(12);
list.add(13);
list.add(14);
cout<<endl<<"len="<<list.length()<<endl;
list.show();
list.delete_pos(6);
list.show();
list.insert_pos(1,666);
list.show();
cout<<list.at(6)<<endl;
return 0;
}
本站资源均来自互联网,仅供研究学习,禁止违法使用和商用,产生法律纠纷本站概不负责!如果侵犯了您的权益请与我们联系!
转载请注明出处: 免费源码网-免费的源码资源网站 » C++ 基础学习
发表评论 取消回复