1

If I push_back a lot of elements and then erase them, the memory will still be reserved, right? So how can I force the vector to reallocate to a smaller size to conserve memory?

I'm not using C++11, so unfortunately I can't use shrink_to_fit.

The answers here do not answer it for me. I don't understand what I'm supposed to swap and how to do it.

Community
  • 1
  • 1
Clonkex
  • 3,373
  • 7
  • 38
  • 55
  • @Kunal: +1 Perfect dupe – legends2k Oct 20 '13 at 07:59
  • @legends2k Can this question be un-duplicate-marked? I don't understand the answers of the other question. I've edited my question. – Clonkex Oct 20 '13 at 22:36
  • The other answers basically mean you copy your elements to another `vector` and then `swap` the contents of that temporary with your current vector. The hope is that the temporary will have a smaller `capacity` because it only ever contained `size` elements. After the swap, the temporary `vector`, now holding the old excess `capacity`, is destroyed and frees the memory. – Blastfurnace Oct 20 '13 at 23:01
  • Ok, I think I get it now. So if I do that in a function, the scope should destroy the temporary `vector` when the function returns, right? So does `swap` do a reallocation? – Clonkex Oct 20 '13 at 23:51
  • `std::vector::swap` is able to simply swap internal pointers between the containers so there's no allocation or copying (it's very fast). In addition `std::swap` is specialized to do the correct thing when given standard library containers. – Blastfurnace Oct 21 '13 at 00:09
  • I just want to add that some of the answers in that other question use an unnamed temporary `vector` so it gets destroyed at the end of the expression. No additional function or nested scope is needed. – Blastfurnace Oct 21 '13 at 00:13
  • What's an unnamed temporary `vector` and how would I use one? I think that's what was confusing about the other answers. – Clonkex Oct 21 '13 at 00:52
  • 1
    When you say `std::vector(v);` it constructs a copy of the vector `v` but it has no name and is then immediately destroyed. Saying `std::vector(v).swap(v);` constructs the vector __and__ calls the `swap` member function to swap the new temporary with `v`. This is the one-step trick everyone used before `shrink_to_fit()` became available. – Blastfurnace Oct 21 '13 at 02:27
  • Here, have an upvote for an excellent explanation :) – Clonkex Oct 21 '13 at 03:24
  • Thanks, this is one of those things that look like magic the first time you see it but is actually quite simple once you understand what's happening. – Blastfurnace Oct 21 '13 at 03:57

0 Answers0