3 ms·
Easily solved manually reserving exponentially. All my projects use some variation of this: https://github.com/facebook/folly/blob/9f125c94e10fd01f5567cdbc317f8
by mandarax8 2y ago
Easily solved manually reserving exponentially. All my projects use some variation of this: https://github.com/facebook/folly/blob/9f125c94e10fd01f5567cdbc317f8026de3a20b5/folly/container/Reserve.h#L49 https://github.com/facebook/folly/blob/9f125c94e10fd01f5567c...
But I've burned myself on this a few times before.
- jstimpfle 2y agoresize(size() + N), resize(size() - N) should do the trick too, unless default constructing your elements is costly or not defined. But I wonder what use case there is where you can't just push_back() one by one? The only potential issue here is that there might be a reallocation happening while append this range of N elements, but can't imagine what might break.
- tialaramex 2y agoIt's a perf leak, not a correctness issue, as with std::unordered_map. So yes, you can just push_back() each item, and as with std::unordered_map the worst case is linearly worse than the Right Thing™. This is a Quality of Implementation issue in the library standard itself.
- jstimpfle 2y agoOk - if the N elements you want to add would cause more than 1 reallocation by constant size factor, yes I can see that. (also I just saw that resize() has the same allocation behaviour as reserve() has, so scratch my suggestion above). Never had a problem myself with that though, my main use case for std::vector is with reserve() right at the beginning and never provoking a reallocation (so I often end up coding up my own container to assert reallocation can't happen accidentally). Sometimes (infrequently) I use the script-style push_back()-only pattern. But I feel very uneasy about uncontrolled reallocations in larger systems, and anyway they constrain the implementation space because of pointer and iterator invaliation.