如何在 C++ 中以特定形式将内容从 1D 数组传输到 2D 数组

how to transfer contents from 1d array to a 2d array in a specific form in c++?

本文关键字:数组 1D 传输 2D C++      更新时间:2023-10-16

结果必须看起来像

// Eg1: 1d array 
b[]={1,2,3}
// 2d array 
// 1 0 3
// 0 2 0
// 1 0 3 
//Eg2: 1d array 
b[]={1,2,3,4}
// 2d array  
// 1 0 0 4 
// 0 2 3 0 
// 0 2 3 0 
// 1 0 0 4
// a[] is 1d array contain input, b[][] is 2d array that will contain result, n is size of the array
//set all b[][] content to 0 first
for (int i = 0; i < n;i++)
{
    for (int j = 0; j < n; j++) b[i][j] = 0;
}
//this is the process to move content from a[] to b[][]
for (int i = 0; i < n ;i++)
{
    b[i][i] = a[i];
    b[n-i-1][i] = a[i];
}

让我们调用数组 A,n 的大小为 A 和矩阵 M (n x n

for(int i = 0; i < n; i++){
    for(int j = 0; j < n; j++){
        M[i][j] = 0;
    }
}
for(int i = 0; i < n; i++){
    M[i][i] = M[n-i-1][i] = A[i];
}

这样的东西应该有效

在运行时,C++中没有 2D 数组这样的东西,至少在没有 ADT 的情况下没有。 二维数组仅在编译时存在,在运行时,您必须线性寻址数组,自己映射索引。