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?
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 , ... }
// In C++ We can Initialize the Variables with Declaration in Structure. Structure members can be initialized using curly braces '{}'.
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!
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.
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}
}
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With