Does clearing a vector affect its capacity?

回眸只為那壹抹淺笑 提交于 2019-11-26 16:58:12

问题


I instantiate an std::vector foo(1000).

foo.size() is now 1000 and foo.capacity() is also 1000.

If I clear the vector with foo.clear(), the size() is now 0, but what is the capacity()? Does the standard say anything about that?


回答1:


No, it doesn't. The capacity of a vector never decreases. That isn't mandated by the standard but it's so both in standard library implementations of VC++ and g++. In order to set the capacity just enough to fit the size, use the famous swap trick

vector<T>().swap(foo);

In C++11 standard, you can do it more explicitly:

foo.shrink_to_fit();



回答2:


To clear a vector and consume as little capacity as possible, use the swap trick:

std::vector<T>().swap(foo);

This creates an empty vector, swaps its internals with foo, and then destroys the temporary vector, getting rid of the elements that once belonged to foo and leaving foo as if it was freshly created.




回答3:


The standard does not say anything about the effect of clear on capacity.




回答4:


No, clear doesn't affect it's capacity(), it's remain the same even if you do clear. If you want to shrink the vector to fit, you can use the following trick after calling clear: foo.swap(vector(foo));



来源:https://stackoverflow.com/questions/6882799/does-clearing-a-vector-affect-its-capacity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!