[回顧性練習2]C++實現數組中插入數據元素(數組)

題目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;
 }

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章