0
我的問題是我想添加一個元素而不詢問用戶的元素。我只想添加一個元素,當我打印所有元素時,包括添加的一個打印元素,而不是首先詢問元素的位置和所有元素。在無位置的數組中添加一個元素
int num,pos;
cout<<"Enter another element: ";
cin>>num;
cout<<"Enter position number: ";
cin>>pos;
cout<<endl;
for(int i=po; i>=pos; i--)
a[i+1]=a[i];
a[pos]=num;
po++;
cout<<"New Array: "<<endl;
for(int i=0; i<po; i++)
cout<<"Element at position "<<i+1<<" is "<<a[i]<<endl;
什麼阻止你完成這個目標? – Caleb
邏輯。 如果我刪除行 a [pos] = num; po ++; 插入的值發生變化。 –
如果你想在數組中插入一個元素,你當然必須移動當前那裏的元素,這可能需要移動其他元素等等。如果您有一個包含5個元素的數組,並且您想要在索引3處插入一個新元素,則必須將索引4和3處的元素分別移至索引5和4。你最好使用'std :: vector'容器,這使得插入變得簡單。 – Caleb