[回顾性练习2]C++实现数组中插入数据元素(数组)

本文介绍了一个使用C++实现的SeqList类,该类能够处理数组数据并支持在指定位置插入新的元素。文章提供了完整的代码示例,包括插入操作的具体实现,并通过测试用例验证了功能的正确性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目2:C++实现数组中插入数据元素

向类SeqList中插入数据,请根据main函数中的调用,完成Insert和output函数。

 

 测试输入期待的输出
测试用例5
1 2 3 4 5
2 9
1 2 3 4 5
1 2 9 3 4 5

代码:

//前置代码
#include<iostream>
#include<stdlib.h>
using namespace std;
class SeqList
{
private:
   int * data;  
   int last; // index of the last element
public:
   SeqList ( int sz );
   ~SeqList ( ) { delete [ ] data; }
   void input ();
   void output() ;
   void Insert   ( const int &x, int i);
}  ;
SeqList::SeqList ( int sz )
{
   if ( sz > 0 )
   { data = new int[sz];
     last = -1;
   }
}
void SeqList:: input()
{
  cin >>last;
  for (int i=0;i<last;i++)
    cin>>data [i];
  last--;
}
//答题区域
void SeqList::Insert(const int &x, int i)
{
    int number=i;
    //int data_cpy[100];
    int *data_cpy;
    data_cpy=new int[100];
    for(int j=0;j<number;j++)
    {
        data_cpy[j]=data[j];
    }
    data_cpy[number]=x;
    for(int j=number;j<=last;j++)
    {
        data_cpy[j+1]=data[j];
    }
    /*for(int iii=0;iii<=last;iii++)
    {
        cout<<data_cpy[iii]<<" ";
        if(iii==last)
            cout<<endl;
    }*/
    data=data_cpy;//疑似错误点
}
void SeqList::output()
{
    last=last+1;
    cout<<*(data+0);
    for(int ii=1;ii<last;ii++){
        cout<<" "<<*(data+ii);
    }
    cout<<endl;

}
//后置代码
int main()
 {
  SeqList myList(50);
  myList.input();
  myList.output();
  int where,value;
  cin >>where;
  cin >>value;
  myList.Insert(value,where);
  myList.output ();
  return 1;
 }

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值