1

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

1 Answer 1

2

std::vector has a constructor that takes 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 .

So you need to switch from () to {}

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

see it live on godbolt.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.