将项目插入数组
Insert item to array
我有 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。
相关文章:
- C++json插入数组
- 正在插入动态数组
- 如何在向量数组中插入元素?
- 将值插入到标准 c++ 数组的正确索引(升序)中
- C++ - 将元素按升序插入数组的 SEG 错误
- 将二维数组的所有元素插入到一维数组中
- 插入数组时违反写访问冲突
- 尝试将对象插入空指针数组时出现分段错误
- 类数组插入函数
- 将数组的元素插入映射的时间复杂度是多少?
- 当索引位于末尾和空数组时,向数组插入元素时出现问题
- C++ 使用数组插入到二叉搜索树中
- 将 2D 数组插入 std::vector 时"cannot convert from 'const GLfloat [12]' to '_Objty'"错误消息
- 如何使用 mongo-cxx-driver 的 **insert** 函数将包含静态数据的多维数组插入到数据库中
- 如何将字符数组插入浮点向量
- 如何将数组插入无序集合
- 用c++将数组数组插入mongo中
- visual C++将整数的二维数组插入到另一个整数的二维阵列中
- 优化数组插入C/ c++
- c++如何将数组插入哈希集