Quote:Original post by Perost
You could also just write a constructor for the struct that initializes the variables. vector will then call that constructor when inserting the elements.
Agreed. Since you're using C++, you should set the initial state of your struct via a constructor rather than memset().
A couple of other points:
1. In C++ it's not necessary to use the struct keyword when a type is referenced, only when it's declared, e.g.:
struct my_struct {};std::vector<my_struct> v;
2. Classes and structs are identical in C++ apart from default privileges, so don't feel you need to use one or the other for technical reasons. (It's conventional to use structs for simple aggregates with public data, but they can still have constructors and so forth).
3. If your struct really
is a POD, then you can initialize it with the {...} syntax as you can with arrays; this should probably be preferred to clearing the struct with memset() when using C++. (Note that the {...} syntax can only be used to initialize the struct, not assign values to it.)
All things considered, initializing via constructor is probably the safest and most convenient option, and obviates the need for setting the state of the object manually after its creation. A quick example:
struct my_struct { int x, y; my_struct(int x = 0, int y = 0) : x(0), y(0) {}};std::vector<my_struct> v(10); // Elements initialized to (0,0) automatically// Do some stuff that modifies the elements...// Reset all elements to (0,0) in one go:std::fill(v.begin(), v.end(), my_struct());// Set all elements to (4,2) in one go:std::fill(v.begin(), v.end(), my_struct(4,2));