如何在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
答案 0 :(得分:6)
您的代码中有#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 style”数组类型的对象将降级为指向数组第一个元素的指针。初始化d
的方法是尝试使用指针值初始化3个矩阵,这将无效。
std::array
是一个类,因此它不会以这种方式降级。