首页 > 解决方案 > 数组 X[n] 仅存储名称。编写算法以在数组中插入或删除 ITEM

问题描述

数组 X[n] 仅存储名称。数组的第一个位置不存储名称,而是存储数组中可用空闲空间的数量。编写算法以在数组中插入或删除 ITEM。

标签: c++arraysoopdata-structures

解决方案


如果你想在一个数组中插入某个pth位置,那么从 i 到最后一个元素的所有元素都应该移动到下一个位置(这将使大小增加)。并将所需的元素放在第 p 个位置。

//you want to insert x in the pth position of A[n]
int temp = x; 
for(int i=p; i<n; i++) {
    swap(temp, A[i]);
}
A[n++] = temp;

同样,要在 pth 位置删除,只需将下一个项目抓取到前一个位置并减小大小:

for(int i=p+1; i<n; i++) {
    A[i-1] = A[i];
}
n--;

推荐阅读