gpt4 book ai didi

c++ - 二维数组的初始化数组

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:25:06 24 4
gpt4 key购买 nike

如何在 C++ 中初始化二维数组的数组(定义如下面的代码)?

#include <iostream>
#include <array>

typedef int arr3by6Int[3][6];
typedef arr3by6Int arr3xarr3by6Int[3];

void print3by6(arr3by6Int arr)
{
for(int i = 0; i < 3; i++)
{
for(int j = 0; j < 6; j++)
{
std::cout << arr[i][j] << " ";
}
std::cout << std::endl;
}
}
int main(int argc, char const *argv[])
{

arr3by6Int a = {
{1,2,3,4,5,6},
{0,0,0,0,0,0},
{2,2,2,2,2,2}
};

arr3by6Int b = {
{2,2,3,4,5,6},
{0,0,0,0,0,0},
{2,2,2,2,2,2}
};

arr3by6Int c = {
{3,2,3,4,5,6},
{0,0,0,0,0,0},
{2,2,2,2,2,2}
};

arr3xarr3by6Int d = { a, b, c };

for(int i = 0; i < 3; i++)
{
print3by6(d[i]);
}
return 0;
}

我收到这些错误:

$ g++ -std=c++11 arrays.cpp -o arrays
arrays.cpp: In function ‘int main(int, const char**)’:
arrays.cpp:39:32: error: array must be initialized with a brace-enclosed initializer
arrays.cpp:39:32: error: array must be initialized with a brace-enclosed initializer
arrays.cpp:39:32: error: array must be initialized with a brace-enclosed initializer

最佳答案

你有 #include <array>在你的代码中,所以你应该使用它。更改类型以使用 std::array<> :

typedef std::array<std::array<int, 6>, 3> arr3by6Int;
typedef std::array<arr3by6Int, 3> arr3xarr3by6Int;

然后,更新您的初始化列表以匹配:

    arr3by6Int a = {
std::array<int, 6>{1,2,3,4,5,6},
std::array<int, 6>{0,0,0,0,0,0},
std::array<int, 6>{2,2,2,2,2,2}
};

arr3by6Int b = {
std::array<int, 6>{2,2,3,4,5,6},
std::array<int, 6>{0,0,0,0,0,0},
std::array<int, 6>{2,2,2,2,2,2}
};

arr3by6Int c = {
std::array<int, 6>{3,2,3,4,5,6},
std::array<int, 6>{0,0,0,0,0,0},
std::array<int, 6>{2,2,2,2,2,2}
};

在大多数情况下,“C 风格”数组类型的对象在表达式中使用时将退化为指向数组第一个元素的指针。你的初始化方式d正在尝试用指针值初始化 3 个矩阵,但这是行不通的。

A std::array是一个类,所以它不会以那种方式降级。

关于c++ - 二维数组的初始化数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19022707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com