You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
std::vector::reserve and reducing memory reallocations initializer lists and emplace_back #539
It's said that you shouldn't add elements to a std::vector while iterating it, because it may cause a reallocation and this will cause all iterators to be left dangling. But what if we use std::vector::reserve before creating those iterators to avoid reallocation? what is the frequency with which std::vector has to reallocate itself when adding new elements? If I know my final size before hand, how much of a performance difference will make to call vector::reserve before my operations?
Length
I don't think this would take more than 10 minutes to explain
There's not much to explain, the standard guarantees that no reallocations will occur if you stay within the reserve size you requested, so if you reserve the final size in advance there will be no reallocations and no iterator invalidations.
changed the title [-]std::vector::reserve and reducing memory reallocations[/-][+]std::vector::reserve and reducing memory reallocations initializer lists and emplace_back[/+]on Oct 6, 2026
Activity
LB-- commentedon Mar 17, 2026
There's not much to explain, the standard guarantees that no reallocations will occur if you stay within the reserve size you requested, so if you reserve the final size in advance there will be no reallocations and no iterator invalidations.
Carmelo908 commentedon Mar 17, 2026
Well, I find it very strange that I don't see anyone talking about reserve (which is also in std::string by the way)
[-]std::vector::reserve and reducing memory reallocations[/-][+]std::vector::reserve and reducing memory reallocations initializer lists and emplace_back[/+]