user2138149
user2138149

Reputation: 17384

C++ STD Containers: std::vector - Is there a way to clear the vector and retain storage allocation?

Is there a way to clear the contents of std::vector while retaining the memory allocation?

The reason for this is that I have a section of code which loops, and I wish to optimize this. I currently have data stored in std::vectors. Each time the loop begins the contents of the vector should be cleared. I then use push_back to enter data into the vector, however since the length of the vector does not often change between iterations of the loop, I would ideally like the vector to retain its allocated storage in memory.

If this is not possible with vector is it possible with another fast access STD type?

Upvotes: 3

Views: 516

Answers (2)

g_bor
g_bor

Reputation: 1092

First have look at here:

Does clearing a vector affect its capacity?

So the standard does not seem to mandate that the capacity is unchanged after clear. But it usually does so in practice.

You can do two things however:

  1. use reseve on the vector at the beginning of the loop, so that you only have one allocation per loop. This is quite simple.
  2. You can use your vector in an indexed way. This seems to be more optimal, but harder to do.

UPDATE: problem with the answer provided here:

What does the standard say about how calling clear on a vector changes the capacity?

The justification in the answer is based on this: No reallocation shall take place during insertions that happen after a call to reserve() until an insertion would make the size of the vector greater than the value of capacity().

This is in the C++ standard.

You can try this:

v.reserve(v.capacity());
v.clear();

However the standard does not specify if the capacity is changed by clear, nor does it specify if the clause for reserve refers to the capacity at the time of the reseve call, or at the time of insert.

UPDATE: for a relevant discussion about this issue on the C++ standards comittee discussion board, please see this: https://cplusplus.github.io/LWG/issue1102

Upvotes: 0

Slava
Slava

Reputation: 44278

Is there a way to clear the contents of std::vector while retaining the memory allocation?

Yes you call std::vector::clear() method, as it is stated in documentation:

Leaves the capacity() of the vector unchanged

Upvotes: 7

Related Questions