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

查看:71
本文介绍了初始化std :: array< struct,size>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试定义和初始化一个struct数组.

  #include< iostream>#include< array>int main(){结构行{双a0;双a1;};//方法0:这种方式有效行c [2] = {{1.0,2.0},{3.0,4.0}};//方法1:在同一行中声明和初始化//std :: array< row,2>a = {{1.0,2.0},{3.0,4.0}};//错误:结构初始化程序中的多余元素std :: array< row,2>a = {{{1.0,2.0},{3.0,4.0}}};//双括号//方法2,声明,然后在不同的行中初始化std :: array< row,2>b;//b = {{1.0,2.0},{3.0,4.0}};//错误:没有可行的重载'='b = {{{{1.0,2.0},{3.0,4.0}}};//双括号返回0;} 

现在我从这篇文章中找到了双括号的作品./p>

只是想知道为什么我们需要额外的一对括号来初始化struct数组?

解决方案

您试图用来初始化/分配您的 std :: array 变量的文字(不带大括号)不匹配这些数组的类型.您需要明确地使每个顶级"元素成为一个 row 对象,例如:

  int main(){结构行{双a0;双a1;};std :: array< row,2>a = {行{1.0,2.0},行{3.0,4.0}};std :: array< row,2>b;b = {行{1.0,2.0},行{3.0,4.0}};返回0;} 

这是因为,没有双花括号,您的RHS文字应该(明确地)成为 std :: array< row,2> 类的对象.但是,使用双花括号时,您正在使用聚合初始化,而不是(复制)赋值(如您所链接的文章中所述).

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. 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).

这篇关于初始化std :: array&lt; struct,size&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆