【问题标题】:How to initialize 2D array to false using ranged-based for loop如何使用基于范围的 for 循环将二维数组初始化为 false
【发布时间】:2016-03-08 03:18:55
【问题描述】:

我目前被困在尝试使用范围基 for 循环来初始化我的数组。

我目前所做的,但它没有在构造函数中使用 C++ 11 数组。构造函数为void,不带参数

//sets everything to flase
for (size_t rowCount = 0; rowCount < NROWS; ++rowCount) {
    for (size_t colCount = 0; colCount < NCOLS; ++colCount){
        m_Floor[rowCount][colCount] = STARTING_PEN_POSITION;
    }
}

到目前为止,我将所有内容都设置为 false(起始笔位置)

for (auto const &row : m_Floor) {
    for (auto const &column : row) {
        //something = STARTING_PEN_POSITION;
    }
}

这个数组在头文件里面

std::array <std::array <bool, NCOLS>, NROWS> m_Floor;

其中 NCOLS 是 size_t 的常量静态值,值为 70

而 NROWS 是 size_t 的常量静态值,值为 22

【问题讨论】:

  • 删除auto之后的const..
  • 只是为了确保如果我删除它然后使用代码m_Floor[row][column] = STARTING_PEN_POSITION; 它不起作用,除非我使用 for 循环的语法错误
  • 你会做column = STARTING_PEN_POSITION;,而不是m_Floor[row][column] = STARTING_PEN_POSITION;。或者更合理的是,您可以将column 重命名为cell,以明确它是对矩阵中单个单元格的引用。或者为了更加简单,您可以删除内部循环,然后执行for (auto&amp; row : m_Floor) { std::fill(std::begin(row), std::end(row), STARTING_PEN_POSITION); }。
  • 感谢您的帮助 我在语法上遇到了很长一段时间的问题,我不知道这会是调用单元格而不是执行 m_Floor 之类的操作

标签: c++ arrays


【解决方案1】:

我不太清楚你的问题的含义,所以我将发布我在上面看到的两个可能问题的答案。首先是为什么您在基于范围的 for 循环中的初始化不起作用。正如 cmets 中所指出的,您需要删除 const。为此参考以下可编译程序

#include <iostream>
#include <array>
using std::array;
using std::cout;
using std::endl;

int main() {

    array<array<int, 10>, 10> two_dimensional_array;
    for (auto& arr : two_dimensional_array) {
        for (auto& ele : arr) {
            ele = 0;
        }
    }

    // print all the values
    for (auto arr : two_dimensional_array) {
        for (auto ele : arr) {
            cout << ele << " ";
        }

        cout << endl;
    }

    return 0;
}

我推断的另一个问题是,您想要一种在构造函数的一行中初始化二维数组的好方法。您可以通过vectors 实现此目的。它们是动态数组,通常是超级优化的。您可以使用vector 构造函数来初始化对象。参考以下代码

#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;

int main() {

    vector<vector<int>> two_dimensional_vector (10, vector<int> (10, 5));
    for (auto& vec : two_dimensional_vector) {
        for (auto ele : vec) {
            cout << ele << " ";
        }

        cout << endl;
    }

    return 0;
}

请注意,我没有使用过 uniform initialization syntax,因为这是可能会造成混淆的地方之一

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-24
    • 1970-01-01
    • 2013-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 1970-01-01
    相关资源
    最近更新 更多