为什么不能使用嵌套初始化列表初始化std::array<std::pair<int,int>,3>,但std::vector<std::pair<int,int>>可以?
请参阅此示例:https : //godbolt.org/z/5PqYWP
为什么这个对数组不能以与对向量相同的方式初始化?
#include <vector>
#include <array>
int main()
{
std::vector<std::pair<int,int>> v{{1,2},{3,4},{5,6}}; // succeeds
std::array <std::pair<int,int>, 3> a{{1,2},{3,4},{5,6}}; // fails to compile
}
回答
您需要添加一对外部大括号来初始化std::array<...>对象本身:
std::array <std::pair<int,int>, 3> a{{{1,2},{3,4},{5,6}}};
最外面的一对用于数组对象,第二对用于对象内部的聚合数组。然后是数组中的元素列表。
- `std::array` is an aggregate, so you need `{}` to construct the `std::array` class, and a `{}` to construct it's member array. `std::vector` has a constructor that takes a `std::initializer_list`, so the `{}` to construct the vector automatically calls that.
- So why is `vector` different from `array`?
回答
类模板的特化std::array表示包含另一个聚合的聚合。
错误的原因是这个声明中的第一个花括号初始化器
std::array <std::pair<int,int>, 3> a{{1,2},{3,4},{5,6}};
^^^^^
被视为内部聚合的初始化程序。在这种情况下,以下花括号初始化器被视为冗余初始化器。
所以你可以写
std::array <std::pair<int, int>, 3> a{ { {1,2},{3,4},{5,6} } };
^ ^
|the inner aggregate|
或喜欢
std::array <std::pair<int, int>, 3> a{ std::make_pair( 1, 2 ), std::make_pair( 3, 4 ), std::make_pair( 5, 6 ) };
- It's worth mentioning that std::array doesn't have a initializer_list constructor, which vector does.
- @iwans std::array is an aggregate. It does not have user declared constructors.:)
THE END
二维码