简体   繁体   English

初始化 std::array<struct, size></struct,>

[英]initialize std::array <struct, size>

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?只是想知道为什么我们需要额外的大括号来初始化结构数组?

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.您尝试用于初始化/分配std::array变量的文字(没有双括号)与那些 arrays 的类型不匹配。 You need to explicitly make each of the 'top-level' elements a row object, like this, for example:您需要明确地将每个“顶级”元素设为row object,例如:

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).这是因为,如果没有双括号,您的 RHS 文字应该是std::array<row,2> class 的对象(明确)。 However, with the double-braces, you are using aggregate initialization rather than (copy) assignment (as mentioned in the post you link).但是,使用双括号,您使用的是聚合初始化而不是(复制)赋值(如您链接的帖子中所述)。

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

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