为什么要使用“双括号"?使用堆叠的std :: array声明多维数组时需要的吗? [英] Why are "double braces" needed in declaration of multi-dimensional array using stacked std::array?

查看:135
本文介绍了为什么要使用“双括号"?使用堆叠的std :: array声明多维数组时需要的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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} }
};

尽管如此,仅用一对这样的单个括号就可以摆脱所有括号的业务:

Although, one can get away all the braces business with only pair of single braces like these:

// 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时,除了最小尺寸外,为什么需要{{?

I'd like to know why {{ are required except on the lowest dimension when using stacked std::array?

godbolt.org/g/b6qfn4

推荐答案

外部括号是 集合初始化语法 和内部是数组初始化语法.

The outer braces are aggregate initializer syntax and the inner are array initializer syntax.

C ++ 14允许大括号.确保您使用的是C ++ 14或更高版本.

C++14 allows brace elision. Make sure you are compiling with C++14 or better.

这篇关于为什么要使用“双括号"?使用堆叠的std :: array声明多维数组时需要的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆