std::vector pushing speed?
c++, containers, performance
Solution
The allocate-copy-delete (or allocate-move-delete in C++11) only happens once each time the vector exceeds its current capacity. With each such reallocation, the capacity doubles. This averages out over time, so the amortized complexity of `push_back()` is constant.
You can pre-allocate the vector's capacity by using its `reserve()` member function.
Problem
I'm using vector to manage my large structure data. But suddenly, when discovering `vector` source code, I am very surprised to see some code below : ``` inline void push_back(const _Ty& _X) {insert(end(), _X); } //... void insert(iterator _P, size_type _M, const _Ty& _X) { ////////////////////////////////////////////////////////////// iterator _S = allocator.allocate(_N, (void *)0); iterator _Q = _Ucopy(_First, _P, _S); _Ufill(_Q, _M, _X); _Ucopy(_P, _Last, _Q + _M); _Destroy(_First, _Last); allocator.deallocate(_First, _End - _First); ////////////////////////////////////////////////////////////// } ``` It's the snippet code which "destroys" then reallocates its whole vector data. It's so annoying, because my structure has a large size and a vector has to manage hundreds of elements, while I only use `vector::operator []` and `vector::push_back()`, especially `pushing back` takes most of my program time (it's time-consuming). In my case, is there any better container which can perform faster than `std::vector`, while I tried to google but no luck?