initialize std::array <struct, size>

拜拜、爱过 提交于 2021-01-28 09:11:08

问题


I am trying to defined and initialize an array of struct.

#include <iostream>
#include <array>

int main() {
    struct row{
        double a0;
        double a1;
    };

    //method 0: this way works
    row c[2] ={{1.0,2.0},{3.0,4.0}};

    //method 1: declare and initialization in same line 
    //std::array<row, 2> a = { {1.0, 2.0}, {3.0, 4.0} };//error: Excess elements in struct initializer
    std::array<row, 2> a = {{ {1.0, 2.0}, {3.0, 4.0} }}; //double brace


    //method 2, declare, then initialize in different line
    std::array<row, 2> b;
    //b = { {1.0, 2.0}, {3.0, 4.0} };//error: No viable overloaded '='
    b = { { {1.0, 2.0}, {3.0, 4.0} } }; //double brace

    return 0;
}

Now I find double brace works from this post.

Just wondering why do we need extra pair of brace to initialize array of struct?


回答1:


The literals (without the doubled braces) you are trying to use to initialize/assign your std::array variables do not match the type of those arrays. You need to explicitly make each of the 'top-level' elements a row object, like this, for example:

int main()
{
    struct row {
        double a0;
        double a1;
    };
    
    std::array<row, 2> a = { row{1.0, 2.0}, row{3.0, 4.0} };

    std::array<row, 2> b;
    b = { row{1.0, 2.0}, row{3.0, 4.0} };

    return 0;
}

This is because, without the double braces, your RHS literals are expected to be objects of the std::array<row,2> class (unambiguously). However, with the double-braces, you are using aggregate initialization rather than (copy) assignment (as mentioned in the post you link).



来源:https://stackoverflow.com/questions/65193350/initialize-stdarray-struct-size

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!