我应该如何大括号初始化std :: pairs的std :: array?

Nei*_*irk 22 c++ c++11 std-pair list-initialization stdarray

std::array<std::pair<int, int>, 2> ids = { { 0, 1 }, { 1, 2 } };
Run Code Online (Sandbox Code Playgroud)

VS2013错误:

错误C2440:'初始化':无法从'int'转换为'std :: pair'没有构造函数可以采用源类型,或构造函数重载解析是不明确的

我究竟做错了什么?

小智 24

添加另一对牙箍.

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };
Run Code Online (Sandbox Code Playgroud)

std::array<T, N>是包含类型成员的聚合类T[N].通常,您可以像使用普通T[N]数组一样初始化,但是当您处理非聚合元素类型时,您可能需要更明确.


Vla*_*cow 18

std::array是一个聚合.它只有一个数据成员 - 指定类型的特化的数组std::array.根据C++标准.(8.5.1聚合)

2当初始化程序列表初始化聚合时,如8.5.4中所述,初始化程序列表的元素作为聚合成员的初始化程序,增加下标或成员顺序

所以这个记录

std::array<std::pair<int, int>, 2> ids = { { 0, 1 }, { 1, 2 } };
Run Code Online (Sandbox Code Playgroud)

有更多的初始化器,然后std :: array中有数据成员.

数据成员std::array又是聚合.您必须为其提供初始化列表.

所以记录看起来像

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };
Run Code Online (Sandbox Code Playgroud)

因为更清楚的是你可以通过以下方式想象初始化

std::array<std::pair<int, int>, 2> ids = { /* an initializer for data member of the array */ };
Run Code Online (Sandbox Code Playgroud)

由于数据成员是聚合的,因此您必须编写

std::array<std::pair<int, int>, 2> ids = { { /* initializers for the aggregate data member*/ } };
Run Code Online (Sandbox Code Playgroud)

最后

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };
Run Code Online (Sandbox Code Playgroud)

  • 如果按标准进行操作,则无法保证`std :: array`只有一个数据成员. (2认同)