On 28.02.2016 15:27, JiiPee wrote:
> We all know the vector class does not have a function to delete extra
> memory from the vector.
You mean shrink_to_fit() is not guaranteed to work? I bet when it does
not then it has good reasons not to.
> So my first question is that why is it not
> there? :) Is there a good reason, as I think its many times needed.
For example? It most probably means an extra copy of the whole array for
no obvious benefit.
If one is working in tight environment where every byte is counted, then
one does not over-allocate arrays in the first place, so there will be
no need to shrink them. Instead, one would use e.g. reserve() to
allocate the correct amount beforehand.
>
> Secondly, we can do it ouselves, and everybody recommends:
>
> (deleting extra memory from a)
> vector<int> a{3,4,7,5,8,7};
> a.push_back(55);
>
> vector<int> temp(a);
> a.swap(temp);
>
> so now a has capacity 7. But I was just thinking, that can't we just do
> a move:
> vector<int> temp(a);
> a = std::move(temp);
That's basically just as good. The swap idiom just predates the C++11
move. And if you have C++11 then you will have shrink_to_fit() which
most probably does the same in a more direct way, so there is no need to
use move.
>
> becouse move will now make sure a is excatcly temp. Why we would like to
> copy stuff from a to temp (with swap) bce temp is not needed anyway ...
> kind of extra work? What is the reason behind swap here?
Swap was a workaround to *avoid* extra copy and extra work in pre-C+11
when there was no move.