Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't std::array<std::pair<int,int>, 3> be initialized using nested initializer lists, but std::vector<std::pair<int,int>> can?

Tags:

See this example: https://godbolt.org/z/5PqYWP

How come this array of pairs can't be initialized in the same way as a vector of pairs?

#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 } 
like image 617
iwans Avatar asked Dec 08 '20 11:12

iwans


People also ask

How do you initialize an array of pairs in C++?

The first element of pair Arr1 is sorted with the pair elements of pair “Arr2”. In the main function, we have initialized the values for pair array “Arr1” and pair array “Arr2”. These sorted arrays and the original pairs array will be displayed by using the cout command.

Does std :: array initialize?

std::array contains a built-in array, which can be initialized via an initializer list, which is what the inner set is. The outer set is for aggregate initialization.

What is c++ initializer_ list?

std::initializer_list initializer_list objects are automatically constructed as if an array of elements of type T was allocated, with each of the elements in the list being copy-initialized to its corresponding element in the array, using any necessary non-narrowing implicit conversions.


1 Answers

You need to add an outer pair of braces to initialize the std::array<...> object itself:

std::array <std::pair<int,int>, 3> a{{{1,2},{3,4},{5,6}}}; 

The outermost pair is for the array object, the second pair is for the aggregate array inside the object. Then the list of elements in the array.

like image 52
Some programmer dude Avatar answered Sep 20 '22 15:09

Some programmer dude