c++实现数组的插入和删除

时间:2021-10-30 22:13:10
#include <iostream> 
using namespace std; 
void Print (int * arr,int len)
{
   for(int i=0;i<len;i++)//用i控制地址arr的累加次数
    cout<<*arr++<<' ';//*的优先级高
}


 void Remove(int * arr,int num,int len)
 {
   for(int i=0;i<len;i++)
   {
      if(arr[i]==num)
         break;
   }
   for(int j=i;j<len-1;j++)
   {         
       arr[j]=arr[j+1];
   }
   //arr[len]=0;这句多余,会自动置0
 }


 void Insert(int *arr ,int num,int pos,int len)
 {   

     for(int i=len;i>=pos;i--)
     {
         arr[i]=arr[i-1];  
     }
     arr[pos-1]=num;
 }


int main()
{
 const int len=10;
 int arry[len]={1,2,3,4,5,6,7,8,9};//剩下默认为0
 Print(&arry[0],len);


cout<<"\ninput the number that you want to remove";
int num;
cin>>num;
Remove(&arry[0],num,len); 
Print(&arry[0],len);



cout<<"\ninput the number and position that you want to insert";
int pos;
cin>>num>>pos;
if(pos>len)
{
    cout<<"the position is bigger than "<<len<< " please input again "<<endl;
    cin>>pos;
}
Insert(&arry[0],num,pos,len);
Print(&arry[0],len);
cout<<endl;

return 0;   
}