Fastest way to reset a value in every struct element of a vector?

c++, performance, vector

Solution

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.

Problem

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?

Original source

Related problems