1. 程式人生 > >c++實現陣列的插入和刪除

c++實現陣列的插入和刪除

#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; }