如何在c ++中将内容从1d数组传输到特定形式的2d数组?

时间:2017-02-01 03:38:58

标签: c++ arrays matrix

结果必须看起来像

// 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

3 个答案:

答案 0 :(得分:1)

// 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];
}

答案 1 :(得分:0)

我们可以将数组 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];
}

这样的事情应该起作用

答案 2 :(得分:-1)

在运行时,C ++中没有2D数组,至少在没有ADT的情况下也是如此。 2D数组仅在编译时存在,在运行时,您必须线性地处理数组,自己映射索引。