将二维数组的所有元素插入到一维数组中
Insert all elements of a 2-dimensional Array into a 1-dimensional Array
你好亲爱的社区,
我正在使用 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 << ' ';
}
相关文章:
- 将二维数组的所有元素插入到一维数组中
- C++语法差异:二维和一维数组(指针算术)
- 将一维数组写入 CSV C++中的不同列?
- C++:将矩阵存储在一维数组中
- 如何在一维数组中的每个元素中都有多个int值
- 以C++填充一维数组
- 用于在一维数组上嵌套循环操作的正确 openmp 指令
- 如何在 <threads> c++ 中使用和一维数组进行矩阵乘法?
- C++按内存地址将多维数组更改为一维数组
- 在 c++ 中返回一维数组时出错
- 一维数组映射方式的性能差异问题
- 如何使用一维数组更改二维数组中的值?
- 使用二维数组作为一维数组是否正确?可能会导致未定义的行为左右?
- 将一维数组转换为二维数组
- 如何使用一维数组列表初始化二维数组
- 在一维数组中对二维进行排序
- 将一维数组的索引转换为二维数组
- 通过访问二维数组实现双线性插值的概念类似于一维数组
- 将二维数组传递到只需要一维数组的函数中(C++)
- 如何在另一个数组中插入多维数组(int而非char)