Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializing struct vector with brace-enclosed initializer list

I initialize normal-type vectors like this:

vector<float> data = {0.0f, 0.0f};

But when I use structure instead of normal-type

struct Vertex
{
    float position[3];
    float color[4];
};
vector<Vertex> data = {{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f}};

I get error could not convert '{{0.0f, 0.0f, 0.0f}, {0.0f, 0.0f, 0.0f, 0.0f}}' from '<brace-enclosed initializer list>' to 'std::vector<Vertex>'. What's wrong with this?

like image 825
Gintas_ Avatar asked Aug 21 '13 10:08

Gintas_


People also ask

How to initialize struct in c++ initializer list?

When initializing an object of struct or union type, the initializer must be a non-empty, (until C23) brace-enclosed, comma-separated list of initializers for the members: = { expression , ... }

How to initialize struct members c++?

// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.

What is brace initialization in C++?

Braced initialization: a review Works in most contexts; No implicit copy construction (as opposed to = ); No more narrowing conversions: the compiler will emit an error in case of truncation instead of silently converting the value; No more most vexing parse!

How do you initialize a union in C++?

A union can have a constructor to initialize any of its members. A union without a constructor can be initialized with another union of the same type, with an expression of the type of the first member of the union, or with an initializer (enclosed in braces) of the type of the first member of the union.


1 Answers

A set of {} is missing:

std::vector<Vertex> data =
{ // for the vector
    { // for a Vertex
        {0.0f, 0.0f, 0.0f},      // for array 'position'
        {0.0f, 0.0f, 0.0f, 0.0f} // for array 'color'
    },
    {
        {0.0f, 0.0f, 0.0f},
        {0.0f, 0.0f, 0.0f, 0.0f}
    }
};
like image 175
hmjd Avatar answered Oct 11 '22 19:10

hmjd