如何调用存储在数组中的数组的值

时间:2019-06-14 16:08:35

标签: c++ arrays class c++11

因此,我试图将数组存储在另一个数组中,并且很难将所有值打印出来。

不确定在c ++中是否可行,但是使用python并已经尝试过。

#define ROW 7

int one[ROW], two[ROW], three[ROW], four[ROW], five[ROW], six[ROW], seven[ROW]; 
int grid[7];

void initialize() {
    for (int i = 0; i < ROW; i++) {
        one[i] = 0;
        two[i] = 0;
        three[i] = 0;
        four[i] = 0;
        five[i] = 0;
        six[i] = 0;
        seven[i] = 0;
    }
    grid[0] = *one;
    grid[1] = *two;
    grid[2] = *three;
    grid[3] = *four;
    grid[4] = *five;
    grid[5] = *six;
    grid[6] = *seven;
}

void print() {
    for (int i = 0; i < 7; i++) {
    int bro = grid[i];
        cout << grid[i] << endl;

        for (int elem : grid[i]) {
            cout << elem << endl;
        }
    }
}

我有这个错误:

error: ‘begin’ was not declared in this scope
             for (int elem : grid[i]) {

error: ‘end’ was not declared in this scope
             for (int elem : grid[i]) {

2 个答案:

答案 0 :(得分:1)

此:

int grid[7];

严格声明一个一维数组。

此:

grid[0] = *one;

它不会将数组分配给第一个元素。对于C样式的数组,*arr等效于arr[0]。因此,您将one中的第一个数字分配给grid[0]

类型不能在C ++中更改。如果需要的话,您必须声明一个2D数组:

int grid[7][7];

如果要复制阵列,原始阵列将无法完成任务。使用std::array将修复副本:

constexpr int row = 7;
std::array<std::array<int, row>, row> grid;
std::array<int, row> one;

// ...

grid[0] = one; // copy one into a row of grid correctly

顺便说一下,全局变量默认为零初始化。

答案 1 :(得分:-1)

我不知道这在c ++中是可行的,但显然是可行的,而且效果很好。

int arr[7][7] = {
        {
            0,1,0,0,0,0,0
        },
        {
            0,0,2,0,0,0,0
        },
        {
            0,0,0,0,0,0,0
        },
        {
            0,0,0,0,0,0,0
        },
        {
            0,0,0,0,0,0,0
        },
        {
            0,0,0,0,0,0,0
        },
        {
            0,0,0,0,0,0,0
        },
    };


for (int i = 0; i < 7; i++) {
        for (int j = 0; j < 7; j++) {
            cout << arr[i][j] << " | ";
        }
        cout << endl;
    }

result:
0 | 1 | 0 | 0 | 0 | 0 | 0 | 
0 | 0 | 2 | 0 | 0 | 0 | 0 | 
0 | 0 | 0 | 0 | 0 | 0 | 0 | 
0 | 0 | 0 | 0 | 0 | 0 | 0 | 
0 | 0 | 0 | 0 | 0 | 0 | 0 | 
0 | 0 | 0 | 0 | 0 | 0 | 0 | 
0 | 0 | 0 | 0 | 0 | 0 | 0 |