为什么使用堆叠的std :: array声明多维数组需要“双括号”?

问题描述 投票:7回答:2
#include <array>
using std::array;

constexpr auto d1=2;
constexpr auto d2=3;
constexpr auto d3=4;

// stacked std::array
using arr_t   = array<int,d1>;
using arr2d_t = array<arr_t,d2>;
using arr3d_t = array<arr2d_t,d3>;
constexpr arr3d_t arr1 = {{
    {{  {1,2},  {3,4},  {5,6}  }},
    {{  {1,2},  {3,4},  {5,6}  }},
    {{  {1,2},  {3,4},  {5,6}  }},
    {{  {1,2},  {3,4},  {5,6}  }}
}};

// built-in array
using carr3d_t = int[d3][d2][d1];
constexpr carr3d_t arr2 = {
    { {1,2}, {3,4}, {5,6} },
    { {1,2}, {3,4}, {5,6} },
    { {1,2}, {3,4}, {5,6} },
    { {1,2}, {3,4}, {5,6} }
};

虽然,人们可以通过这样的一对单支撑来逃脱所有支撑业务:

// getaway with one-dimensional declaration
constexpr arr3d_t arr3 = {
    1,2,  3,4,  5,6,
    1,2,  3,4,  5,6,
    1,2,  3,4,  5,6,
    1,2,  3,4,  5,6
};
constexpr carr3d_t arr4 = {
    1,2,  3,4,  5,6,
    1,2,  3,4,  5,6,
    1,2,  3,4,  5,6,
    1,2,  3,4,  5,6
};

我想知道为什么{{是必需的,除了在使用堆栈std :: array时的最低维度?

godbolt.org/g/b6qfn4

c++ arrays c++11 stdarray
2个回答
6
投票

外括号是aggregate initializer syntax,内部是数组初始化语法。

C ++ 14允许括号省略。确保使用C ++ 14或更高版本进行编译。


3
投票

您的类型arr_tarr2d_tarr3d_tcarr3d_t是聚合类型。它们是聚合类型,因为std::array本身是聚合类型。它们的对象使用aggregate initialization初始化,并且在使用C ++ 11支持进行编译时,您需要围绕嵌套初始化程序的(额外){}括号。从C ++ 14标准开始:

嵌套初始化程序列表周围的大括号可以省略(省略)

© www.soinside.com 2019 - 2024. All rights reserved.