有没有办法在不在 C++ 中循环的情况下用输入的维度初始化二维数组中的所有项目?

Is there a way to initialize all items in a 2d array with inputted dimensions without looping in C++?

有没有一种方法可以在不在 C++ 中循环的情况下将具有控制台输入尺寸的二维数组中的所有项目初始化为指定项目? 例如,假设我有两个整数 x 和 y,以及一个名为 grid:

的二维数组
#include <iostream>

int main() {
    int x, y;
    std::cout << "Enter the dimensions of the array separated by a space: ";
    std::cin >> x >> y;
    bool grid [x][y] {/*all false*/};
    // other code
    return 0;
}

有什么方法可以按照上面的格式初始化grid中的每一项吗?我试过了:

    bool grid [x][y] {false};

但这只是将第一项设置为 false。

您可以使用 memset。您可以阅读更多相关信息 here

它的作用是将您指定的内存块设置为您传递的内容。

  • 如果您确实希望值是 false,您可以使用 bool grid[x][y] = {};。这是可行的,因为大括号给出了一个初始值列表,完成后,数组中的所有剩余值都被零初始化,这将给出一个 false 值。注意:这是有效的 C++,但 C 不允许空的初始化列表,因此对于普通 C,您需要 bool grid[x][y] = {false};.
  • 正如 bhristov 上面提到的,您可以使用 memset。但在我看来这不是好的 c++ 风格。
  • 您可以使用std::fill或std::fill_n,因为二维数组是一组长度为x * y的连续值。这具有允许您指定其他值的优点,而不仅仅是 false.

bool grid [x][y]xy 不是 constexpr 时使 grid 成为 VLA(可变长度数组)。 VLA:s 在标准 C++ 中不存在,仅在某些编译器中作为扩展可用。我建议你不要使用它们。旁注:您通常希望交换 xy,因为数组在内存中以行主要顺序存储,并且如果逐行访问元素,访问元素可能会更快,因为如何缓存工作。

惯用的方法是使用 std::vector.

#include <iostream>
#include <vector>

int main() {
    size_t x, y; // a suiteable unsigned type

    std::cout << "Enter the dimensions of the array separated by a space: ";
    std::cin >> x >> y;

    // create a 2D vector, all initialized to "false"
    std::vector<std::vector<bool>> grid(y, std::vector<bool>(x, false));  

    for(size_t yval = 0; yval < grid.size(); ++yval) {
        for(size_t xval = 0; xval < grid[yval].size(); ++xval) {
            std::cout << grid[yval][xval];
        }
        std::cout << '\n';
    }  
}

可变长度数组不是标准的 C++ 功能。此外,即使在标准中包含可变长度数组的 C 中,您也不能在声明中初始化它们。

在 C++ 中,您应该使用标准 class 模板 std::vector

例如

int x, y;
std::cout << "Enter the dimensions of the array separated by a space: ";
std::cin >> x >> y;
std::vector<std::vector<bool>> grid( x, std::vector<bool>( y ) );

最后一条语句声明了一个 vector of vector,其所有元素都将设置为 false。

是的,您可以使用 memset 进行初始化。

#include <bits/stdc++.h>
using namespace std;
int main()
{
    int row=5;
    int col=6;
    int mat[row][col];
    memset(mat, 0, sizeof(mat[0][0]) * row * col);
    
    return 0;
}