将项插入数组

时间:2015-04-25 12:20:41

标签: c++ arrays

我有3个数组,每个数组包含5个元素(最大大小为5)。我想要做的是插入一个项目,例如,到位置7.最终结果是项目应该放在索引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 ++做到这一点?

1 个答案:

答案 0 :(得分:0)

你还没有告诉我们很多真正的问题,但这里是一个通用解决方案的概述。要访问位置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。