简体   繁体   English

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

[英]How should I brace-initialize an std::array of std::pairs?

std::array<std::pair<int, int>, 2> ids = { { 0, 1 }, { 1, 2 } };

VS2013 error: VS2013错误:

error C2440: 'initializing' : cannot convert from 'int' to 'std::pair' No constructor could take the source type, or constructor overload resolution was ambiguous` 错误C2440:'初始化':无法从'int'转换为'std :: pair'没有构造函数可以采用源类型,或构造函数重载解析是不明确的

What am I doing wrong? 我究竟做错了什么?

Add another pair of braces. 添加另一对牙箍。

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };

std::array<T, N> is an aggregate class containing a member of type T[N] . std::array<T, N>是一个包含T[N]类型成员的聚合类。 Usually, you can initialise that the same way you would a plain T[N] array, but when you're dealing with a non-aggregate element type, you may need to be more explicit. 通常,您可以像普通T[N]数组一样初始化,但是当您处理非聚合元素类型时,您可能需要更明确。

std::array is an aggregate. std::array是一个聚合。 It has only one data member - an array of the specified type of the std::array specialization. 它只有一个数据成员 - 指定类型的std::array According to the C++ Standard. 根据C ++标准。 (8.5.1 Aggregates) (8.5.1聚合)

2 When an aggregate is initialized by an initializer list, as specified in 8.5.4, the elements of the initializer list are taken as initializers for the members of the aggregate, in increasing subscript or member order 2当初始化程序列表初始化聚合时,如8.5.4中所述,初始化程序列表的元素作为聚合成员的初始化程序,增加下标或成员顺序

So this record 所以这个记录

std::array<std::pair<int, int>, 2> ids = { { 0, 1 }, { 1, 2 } };

has more initializers then there are data members in std::array. 有更多的初始化器,然后std :: array中有数据成员。

The data member of std::array is in turn an aggregate. std::array的数据成员又是一个聚合。 You have to provide for it an initializer list. 您必须为其提供初始化列表。

So the record will look like 所以记录看起来像

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };

For it would be more clear you can imagine the initialization the following way 因为更清楚的是你可以通过以下方式想象初始化

std::array<std::pair<int, int>, 2> ids = { /* an initializer for data member of the array */ };

As the data member is aggregate then you have to write 由于数据成员是聚合的,因此您必须编写

std::array<std::pair<int, int>, 2> ids = { { /* initializers for the aggregate data member*/ } };

And at last 最后

std::array<std::pair<int, int>, 2> ids = { { { 0, 1 }, { 1, 2 } } };

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM