C++ day2

题目:使用C++手动封装一个顺序表,包含成员数组一个,成员变量N个

#include <iostream>

using namespace std;

//类型重命名
using datatype = int;     //typedef int datatype;
#define MAX 30


struct  SeqList
{
    private:
       // datatype data[MAX] = {0};                //顺序表的数组
        datatype *data;                //顺序表的数组
        int size = 0;                      //数组的大小
        int len = 0;                     //顺序表实际长度


     public:
         //初始化函数
         void init(int s)
         {
             size = s;            //当前数组的最大容量
             data = new datatype(size);      //在堆区申请一个顺序表容器
         }
         //要实现的函数
         //判空函数
         bool empty();
         //判满函数
         bool full();
         //添加数据函数
         bool add(datatype e);
         //求当前顺序表的实际长度
         int length();
         //展示数据
         void show();

         //任意位置插入函数
         bool insert_pos(int pos, datatype e);
         //任意位置删除函数
         bool delete_pos(int pos);
         //访问容器中任意一个元素 at
         datatype at(int index);
};

//判空函数
bool SeqList::empty()
{
    return len==0;
}
//盘满函数
bool SeqList::full()
{
    return len==size;
}
//添加数据函数
bool SeqList::add(datatype e)
{
    if(full())
    {
        cout<<"顺序表已满"<<endl;
        return false;
    }
    data[len++]=e;
    return true;
}
//求顺序表得实际长度
int SeqList::length()
{
    if(empty())
    {
        return false;
    }
    return len;
}
//展示函数
void SeqList::show()
{
    for(int i=0;i<len;i++)
    {
        cout<<data[i]<<" ";
    }
    cout<<""<<endl;
}
//返回任意位置函数
bool SeqList::delete_pos(int pos)
{
    if(empty())
    {
        return false;
    }
    for(int i=pos;i<len-1;i++)
    {
        data[i]=data[i+1];
    }
    len--;
    cout<<"删除成功"<<endl;
    return true;
}
//任意位置插入函数
bool SeqList::insert_pos(int pos, datatype e)
{
    if(full())
    {
        cout<<"顺序表已满"<<endl;
        return false;
    }
    for(int i=len-1;i>=pos;i--)
    {
        data[i+1]=data[i];
    }
    data[pos]=e;
    len++;
    cout<<"插入成功"<<endl;
    return true;
}


//访问任意元素
datatype SeqList::at(int index)
{
    return data[index];
}



int main()
{
    SeqList list;
    list.init(MAX);
    //添加数据
    list.add(5);
    list.add(2);
    list.add(0);
    //任意位置插入
    list.insert_pos(1,1);
    list.insert_pos(2,3);
    list.insert_pos(3,1);
    list.insert_pos(4,4);
    //展示数据
    list.show();
    //删除
    list.delete_pos(0);
    list.delete_pos(5);
    list.delete_pos(5);
    //展示数据
    list.show();
    //访问数据
    cout<<"访问数据:"<<list.at(3)<<endl;
    //返回数据表长度
    cout<<"数据表长度:"<<list.length()<<endl;
    return 0;
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值