将二维数组的所有元素插入到一维数组中

Insert all elements of a 2-dimensional Array into a 1-dimensional Array

本文关键字:插入 一维数组 元素 二维数组      更新时间:2023-10-16

你好亲爱的社区,

我正在使用 c++ 数组(静态和动态数组(。我的静态数组A1的大小为 [30][30],动态数组A2长为 [30*30]。 我想做的是将A1复制到A2中。

数组A1&A2的内容填充由 0 到 9 之间的随机整数填充。

这是我以前的解决方案方法:(我认为到目前为止我将副本制作成A2,但我无法弄清楚如何返回数组A2

int main() {
//Array 2-Dimensional
int A1[30][30] = { 0 };
int *A2 = new int[30*30];
int x, j, z;
for (x = 0; x < 30; x++) {
for (j = 0; j < 30; j++) {
A1[x][j] = rand() % 10;
printf("%d ", A1[x][j]);
for (z = 0; z < 30 * 30; z++) {
A2[z] = A1[x][j]; 
}
}
printf("n");           
}
system("Pause");
return 0;
}

你不需要三个嵌套循环来实现这一点。诀窍是使用静态数组的两个索引来计算动态数组的索引。

下面是一个完整的示例,介绍如何在C++中仅使用两个嵌套循环执行此操作:

#include <iostream>
const constexpr static int SIZE = 30;
int main() {
int A1[SIZE][SIZE] = { 0 };
int *A2 = new int[SIZE * SIZE];
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
A1[row][col] = rand() % 10;
std::cout << A1[row][col] << ' ';
// calculates the index for A2
int index = row * SIZE + col;
A2[index] = A1[row][col];
}
std::cout << 'n';
}
// A simple loop just to print the contents of A2
for (int i = 0; i < SIZE * SIZE; i++) {
std::cout << A2[i] << ' ';
}
// don't forget to deallocate A2
delete[] A2;
return 0;
}

等等。哪种语言??C++?

#include <cstddef>
#include <cstdlib>
#include <ctime>
#include <array>
#include <vector>
#include <algorithm>
#include <iostream>
int main()
{
constexpr std::size_t num_elements{ 30 };
constexpr std::size_t max_idx{ num_elements - 1 };
std::array<std::array<int, num_elements>, num_elements> A1;
std::vector<int> A2(num_elements * num_elements);
std::srand(static_cast<unsigned>(std::time(nullptr)));
std::generate(&A1[0][0], &A1[max_idx][max_idx] + 1, [](){ return rand() % 10; });
for (auto const &row : A1) {
for (auto const &col : row)
std::cout << col << ' ';
std::cout.put('n');
}
std::copy(&A1[0][0], &A1[max_idx][max_idx] + 1, A2.begin());
for (auto const &i : A2)
std::cout << i << ' ';
}