Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to release memory from std::deque?

Tags:

c++

stl

deque

I'm using a std::deque to store a fairly large number of objects. If I remove a bunch of those objects, it appears to me that its memory usage does not decrease, in a similar fashion to std::vector.

Is there a way to reduce it? I know that in a vector you have to use the 'swap trick', which I assume would work here too, but I'd rather avoid that since it would require copying all the elements left in the container (and thus requires that you have enough memory to store every object twice). I'm not intimately familiar with the implementation of deque, but my understanding of it is that it might be possible to achieve such a thing without lots of copies (whereas with a vector it's clearly not).

I'm using the VC++ (Dinkumware) STL, if that makes any difference.

like image 595
Peter Avatar asked Aug 07 '09 00:08

Peter


2 Answers

There is no way to do this directly in a std::deque. However, it's easy to do by using a temporary (which is basically what happens in a std::vector when you shrink it's capacity).

Here is a good article on std::deque, comparing it to std::vector. The very bottom shows a clean way to swap out and shrink a vector, which works the same with deque.

like image 60
Reed Copsey Avatar answered Oct 05 '22 17:10

Reed Copsey


As added information to this:

In C++0x/C++11, deque (and several other containers) has a new function called "shrink_to_fit" which will remove the excess items and basically align capacity() == size()

like image 28
David Avatar answered Oct 05 '22 17:10

David