Let’s I have
struct Vector {
float i,j,k;
}
I want to zero all elements of vec declared below (i,j,k=0)
std::vector <Vector> vec;
vec.resize(num,0);
I don’t want to use reserve() and then push_back() zeroes one by one.
Another thing is, after succesfully initializing vec, I want to set all members of vec to zero again after it is manipulated. Is there something like memset for vectors?
EDIT:
I compared all of the methods in Mike Seymour’s and Xeo’s answers and as a result
size_t size = vec.size(); is the fastest if they are repeated frequently in a loop.
vec.clear();
vec.resize(size);
That’s very simple:
or initialise it with the required size:
Both the constructor and
resizewill fill new elements with value-initialised objects. A value-initialised object of a type with no default constructor (such as yourVector) will have all numeric members initialised to zero.To reset everything to zero, either
or:
or, less efficiently but with a strong exception guarantee: