I am guaranteed to initialize a vector of struct with each element initialized to zero with that code ?
#include <vector>
struct A {
int a, b;
float f;
};
int main()
{
// 100 A's initialized to zero (a=0, b=0, f=0.0)
// std::vector<A> my_vector(100, {}); does not compile
std::vector<A> my_vector(100, A{});
}
>Solution :
Yes it is guaranteed since A{} is value initialization and from cppreference:
Zero initialization is performed in the following situations:
- As part of value-initialization sequence for non-class types and for members of value-initialized class types that have no constructors, including value initialization of elements of aggregates for which no initializers are provided.
You can also use:
std::vector<A> my_vector(100, {0,1,1});