The easiest way that doesn't change your code too much is to simply use the link instead of the instance. So:
SomeStruct & info = myVector[i];
The next simple way is to switch from using a loop with an index, so that:
for (std::vector<SomeStruct>::iterator it = myVector.begin(); it != myVector.end(); ++it) { SomeStruct & info = *it; // do stuff here }
With STL, you can go even further, especially if you have a C ++ 11 compiler, for example:
std::for_each(std::begin(myVector), std::end(myVector), [](SomeStruct & info) { });
Also not directly related to your question, but if you add a method to a structure that calculates the frequency, the code becomes much cleaner, for example, following the last example you could do:
std::for_each(std::begin(myVector), std::end(myVector), std::mem_fun(&SomeStruct::calculateFrequency));
This will also work without the C ++ 11 compiler if you change the calls to std::begin(myVector)
to myVector.begin()
and the same for the end.
source share