Very much like this question, except that instead vector<int>
I have vector<struct myType>
.
If I want to reset (or for that matter, set to some value) myType.myVar
for every element in the vector, what's the most efficient method?
Right now I'm iterating through:
for(int i=0; i<myVec.size(); i++) myVec.at(i).myVar = 0;
But since vectors are guaranteed to be stored contiguously, there's surely a better way?
vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.
Removing elements from 2D vectors in C++ Similar to the 'insert()' function, it requires a positional argument as an iterator. To remove all the vectors from the 2-D vector, 'clear()' function can be used.
Resetting will need to traverse every element of the vector, so it will need at least O(n) complexity. Your current algorithm takes O(n).
In this particular case you can use operator[]
instead of at
(that might throw an exception). But I doubt that's the bottleneck of your application.
On this note you should probably use std::fill
:
std::fill(myVec.begin(), myVec.end(), 0);
But unless you want to go byte level and set a chunk of memory to 0
, which will not only cause you headaches but will also make you lose portability in most cases, there's nothing to improve here.
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