[Solved] speeding vector push_back [closed]


Indeed push_back may trigger reallocation, which is a slow process.
It will not do so on every single push_back though, instead it will reserve exponentially more memory each time, so explicit reserve only makes sense if you have a good approximation of resulting vector size beforehand.

In other words, std::vector already takes care of what you are suggesting in your code.

Another point: there is a reserve method that serves the purpose much better than inserting and erasing elements, most notably it does not create and destroy actual objects.

Ironically as @Sopel mentioned replacing insert/erase with reserve in your class would disable vector’s growth amortization, making your code a nice example of several mistakes (somewhat) cancelling each other.

3

solved speeding vector push_back [closed]