2 ms·
reserve can be very easily misused. For example, let's assume a function append_10_items_to_vector. Since we're adding 10 items, we may get a better performan
by yongjik 13y ago
reserve can be very easily misused. For example, let's assume a function append_10_items_to_vector. Since we're adding 10 items, we may get a better performance if we call reserve() before 10 push_back()s. Right?
Not always. If we have a loop that calls our append_10_items_to_vector N times (on the same vector), then your reserve() just transformed the loop into O(N^2) code. Without reserve, it would be O(N).
As a rule of thumb, use reserve only if you are really sure that nobody's ever going to add anything more to your vector in the future.