Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Initialize a std::vector of structures to zero

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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}); 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading