使用循环在C ++中使用1D数组将值添加到2D数组中

时间:2017-08-08 16:57:34

标签: c++ arrays loops

我有一个1D数组和带有一些值的2D数组。我想使用循环将1D数组的值添加到2D数组中。

到目前为止,我有以下代码:

#include <iostream>
#include <conio.h>          //for _kbhit
using namespace std;
#define MAX_N 100

int c[MAX_N] = {21, 12, 23, 34, 15, 16};

int b[MAX_N][MAX_N] = {
                        { 10 , 11 , 20 },
                        { 22 , 30 , 33 },
                        { 40 , 44 , 50 }, 
                        { 55 , 60 , 66 }
                      };
int main()
{

    int i,j,k,l;
    int idx = 0;

    for( i=0 ; i<2 ; i++ )
       {
           for( j=0 ; j<3 ; j++ )
              {
                  b[i][j] = c[idx++];
              } 
       }


    for ( k = 0 ; k < 2 ; k++)
    {
        for (l = 0 ; l < 3 ; l++)
        {
            cout << b[k][l] << " " ;
        } cout << endl;
    }
cout << "\n\nHit<enter> to finish";
while ( !_kbhit());
return (0);
}

它不能按我的意愿工作。设计的输出是:

10 11 20
22 30 33
40 44 50 
55 60 66
21 12 23
34 15 16

请帮忙吗? 谢谢!

2 个答案:

答案 0 :(得分:0)

如前所述,您的初始for循环会覆盖您的表。有更多的代码可以真正添加,但一般来看下面的代码,看看它是否有帮助:

int nextRow = 4;
int itemsToAdd = 6;
int rowsToAdd = itemsToAdd/3;
int additional = itemsToAdd%3;  // just added as hint for incomplete rows
int totalRows = nextRow + rowsToAdd;
int idx = 0;

for( i=nextRow; i<totalRows ; i++ )
{
    for( j=0 ; j<3 ; j++ )
    {
        b[i][j] = c[idx++];
    } 
}

最后,您需要更新输出循环以使用totalRows变量。

答案 1 :(得分:-1)

尝试跟踪您添加到2D阵列的每个元素。现在你只需创建一个新数组而不添加值