I’ve got a vector of structs in C++ and I would like to modify each item individually. I found that doing SomeStruct info = myVector[i] gives me a copy of the item, so if I modify it nothing will be changed. So right now I’m resetting the item like that: myVector[i] = info. Is there a more efficient way do that? One that won’t involve a copy operation?
This is my current code:
struct CharacterInfo {
QChar character;
int occurrences;
double frequency;
};
std::vector<CharacterInfo> characterInfos;
// Some code to populate the vector
for (unsigned i = 0; i < characterInfos.size(); i++) {
CharacterInfo info = characterInfos[i];
info.frequency = (double)info.occurrences / (double)totalOccurrences;
characterInfos[i] = info; // how to avoid this?
}
The simplest way which doesn’t change too much of your code is just to use a reference instead of an instance. So:
The next easiest way is to change from using a loop with an index, so like:
With the STL you can go even further, especially if you have a C++11 capable compiler, for instance:
Also not related to your question directly, but if you add a method to the struct that computes the frequency, the code becomes much cleaner, for instance following from the last example you could do:
This will also work without a C++11 compiler if you change the calls to
std::begin(myVector)withmyVector.begin()and the same for end.