Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 886
OJFord Avatar asked Mar 27 '14 19:03

OJFord


People also ask

How do you clear the elements of a vector?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.

How do you clear all elements in a 2D vector?

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.


1 Answers

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.

like image 85
Shoe Avatar answered Sep 19 '22 20:09

Shoe