c++: allocating space for a container

Please tell me, if I have a container and I know how many elements there will be in it, to speed up the work, I can select them initially, for example like this:

std::vector<int> storage;
storage.reserve(10000);

And what happens when I clean the elements from the container?

storage.clear();

Do I need to reserve the volume again, or is it possible to make such a clear() so that the reserved memory remains

Author: Zhihar, 2018-11-16

4 answers

The clear function does not release the reserved memory. To release it, you need to call shrink_to_fit after clear.

 1
Author: freim, 2018-11-16 12:21:11

According to the documentation for the method std::vector::clear() (free translation):

Changing the actual size of the memory block is not guaranteed, and therefore there is no guarantee of changing the capacity of the vector. To force memory release, use swap:

vector<T>().swap(x);   // высвобождаем память из-под x

A reallocation is not guaranteed to happen, and the vector capacity is not guaranteed to change due to calling this function. A typical alternative that forces a reallocation is to use swap:

vector<T>().swap(x);   // clear x reallocating 

The reason is the high cost of accessing the memory manager. After all, it must take a global lock, at least partially run through the list of allocated blocks, and sometimes merge adjacent free blocks.

So you can safely rely on the fact that the memory does not need to be re-reserved.

 3
Author: Arhadthedev, 2018-11-16 12:24:47

Yes, you need to call reserve again. After clearing with clear, the vector is formally considered empty and you should not make assumptions about what the vector actually did with the memory. Since the standard does not require or promise anything like this, that is, a vector can free up all or part of the memory, or release nothing. Nothing terrible will happen if the memory is not released, and you re-called reserve. On the other hand, if the memory is freed, your repeated call to reserve will do the same as and the first one will reserve the required amount of memory.

 1
Author: Cerbo, 2018-11-25 10:44:35

That is, from all of the above, it still turns out that if the work with the container is constantly going on, then you can not really bother after cleaning the container with memory reservation, since the old one is not given to the system and can be reused?

It will have the same effect, as if I reserve memory every time, i.e. when adding an element, no extra time will be spent on allocating memory for the element.

 0
Author: Zhihar, 2018-11-16 14:48:41