First have look at here:
Does clearing a vector affect its capacity?
So the standard does not seem to mandate that the capacity is unchanged after clear. But it usually does so in practice.
You can do two things however:
- use reseve on the vector at the beginning of the loop, so that you only have one allocation per loop. This is quite simple.
- You can use your vector in an indexed way. This seems to be more optimal, but harder to do.
UPDATE: problem with the answer provided here:
What does the standard say about how calling clear on a vector changes the capacity?
The justification in the answer is based on this:
No reallocation shall take place during insertions that happen after a call to reserve()
until an insertion would make the size of the vector greater than the value of capacity().
This is in the C++ standard.
You can try this:
v.reserve(v.capacity());
v.clear();
However the standard does not specify if the capacity is changed by clear, nor does it specify if the clause for reserve refers to the capacity at the time of the reseve call, or at the time of insert.
UPDATE: for a relevant discussion about this issue on the C++ standards comittee discussion board, please see this: https://cplusplus.github.io/LWG/issue1102