简体   繁体   English

如何使用initializer_list创建C ++ <array> 结构?

[英]How to use an initializer_list to create a C++ <array> of structures?

The following code works as expected to initialize a vector of structs: 以下代码按预期工作以初始化结构向量:

#include <array>
struct node
{
    std::string name;
    std::string value;
};

const std::vector<node> reqFields ({
    { "query", tmpEmail },
    { "firstname", firstName },
    { "lastname", lastName }
});

I want to optimize my code a bit to use a C++ 11 array instead, given that my data is static. 考虑到我的数据是静态的,我想稍微优化一下代码以使用C ++ 11数组。 However, the following won't compile: 但是,以下内容不会编译:

const std::array<node, 3>({
    { "query", tmpEmail },
    { "firstname", firstName },
    { "lastname", lastName }
});

What is the right syntax to initialize the array? 初始化数组的正确语法是什么? or maybe this is something that Visual Studio 15 has trouble with? 还是这是Visual Studio 15遇到的问题?

std::vector has a constructor that takes initializer_list : std :: vector具有采用initializer_list的构造initializer_list

vector( std::initializer_list<T> init,
    const Allocator& alloc = Allocator() ); 

but std::array is an aggregate and follows the rules of aggregate initialization . 但是std :: array是聚合,并遵循聚合初始化规则。

So you need to switch from () to {} 因此,您需要从()切换到{}

const std::array<node, 3> reqFields {
    {{ "query", "tmp" },
    { "firstname", "firstName" },
    { "lastname", "lastName" }}
};

see it live on godbolt . 看到它活着了

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

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