【问题标题】:How do I call the values of arrays that are stored in an array如何调用存储在数组中的数组的值
【发布时间】:2019-10-29 07:21:55
【问题描述】:

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

不确定这在 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]) {

【问题讨论】:

  • 与其拥有 7 个并行数组,不如拥有一个包含 7 个整数的结构的数组。
  • 另一个想法是有一个二维矩阵。使用 2D 矩阵,您无需指定每个变量的名称。
  • 我支持@molbdnilo 的评论。如果您正在使用它,请提供一个minimal reproducible example 来重现您的问题。
  • 您发布的代码中既没有“开始”也没有“结束”。请提供更多背景信息。
  • grid[i]one int,而不是数组。 *one*two 等等也是如此。考虑投资一本好书;通过反复试验学习既费时又会滋生迷信。

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


【解决方案1】:

这个:

int grid[7];

严格声明一维数组。

这个:

grid[0] = *one;

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

类型不能在 C++ 中改变。如果这是你想要的,你必须声明一个二维数组:

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

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

【讨论】:

  • 谢谢,我已经尝试过二维方法并且成功了:)
  • @princejoogie 好!另外,尝试使用constexpr int 代替宏,如果可能,使用std::array
  • constexpr 和 const 有什么区别?
  • const 是一个变量,它的值不能改变。 constexpr 是一个常量变量,它的值在编译时可用。
【解决方案2】:

我不知道这在 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 |

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 2014-08-18
    • 1970-01-01
    • 1970-01-01
    • 2014-07-26
    • 1970-01-01
    • 2020-08-06
    • 1970-01-01
    相关资源
    最近更新 更多