将项目插入数组

Insert item to array

本文关键字:数组 插入 项目      更新时间:2023-10-16

我有 3 个数组,每个数组包含 5 个元素(最大大小为 5)。我想做的是插入一个项目,例如,位置 7。最终结果是该项目应放置在索引 2 处的第 2 个数组中,然后使用 1 个元素创建第 4 个数组(从第 3 个数组的最后一项)。

                                result
array1                          array1
    - item1 (position 0)            - item1 (position 0)
    - item2 (position 1)            - item2 (position 1)
    - item3 (position 2)            - item3 (position 2)
    - item4 (position 3)            - item4 (position 3)
    - item5 (position 4)            - item5 (position 4)
array2                          array2
    - item1 (position 5)            - item1 (position 5)
    - item2 (position 6)            - item2 (position 6)
    - item3 (position 7)            - item3 (position 7) -> new_item
    - item4 (position 8)            - item4 (position 8)
    - item5 (position 9)            - item5 (position 9)
array3                          array3
    - item1 (position 10)           - item1 (position 10)
    - item2 (position 11)           - item2 (position 11)
    - item3 (position 12)           - item3 (position 12)
    - item4 (position 13)           - item4 (position 13)
    - item5 (position 14)           - item5 (position 14)
                                array4
                                    - item1 (position 15)

而且,如果要将项目放在位置 12,则结果应该是 array3 的 item3。

如何在 c++ 中执行此操作?

你还没有告诉我们太多关于真正问题的信息,但这里有一个通用解决方案的大纲。要访问位置 13:

unsigned int n = 13;
// This is the zero-based index to find the array.
unsigned int i = n/5;
// This is the zero-based index of the element within the array.
unsigned int j = n%5;

对于插入,此函数将在位置 k 处插入项目 x 并返回最后一个项目(必须删除以腾出空间):

int insert(Item *A, Item x, unsigned int k)
{
  Item ret = A[4];
  for(unsigned int j=4; j>k; --j)
    A[j]=A[j-1];
  A[k] = x;
  return(ret);
}

因此,如果您有 3 个数组,请在位置 7 插入一个项目 x:

Item y; 
y = insert(array2, x, 2);
y = insert(array3, y, 0);

现在用你喜欢的任何方法创建一个新的 array4,并设置 array4[0]=y。