3
std::vector 的 reserve, resize, clear, shrink_to_fit 的内存逻辑
source link: https://zhiqiang.org/coding/std-vector-size-and-capacity.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
std::vector 的 reserve, resize, clear, shrink_to_fit 的内存逻辑
std::vector
有两个大小,一个是数据大小,即size()
,另一个是容量,和占用内存空间相关,即capacity()
。
reserve(n)
会预留容量,如果n
小于当前容量,什么也不会做。
resize(n)
会调整数据大小,当n
小于当前数据大小时,后面的数据将被清空,但容量不变;当n
大于当前容量时,还会扩充容量。
clear()
等价于resize(0)
,只清除数据,不清除空间,注意容量保持不变!这和clear
的语意会有区别。如果要实现真正的清除(既清除数据,也清除空间),需要用下面两种方法:
v.clear()
之后,再v.shrink_to_fit(0)
。v.clear()
之后,再std::vector<T>{}.swap(v)
。
Q. E. D.
前一篇:
西山公园后山 9 公里大环线
这个路线和之前的10 公里大环线类似,水库沿山脊的路线因为植被过于茂密,以及有很多蜘蛛网,改成从水库直接上快活林。因此路程稍微短了一些。但这段路也很有意思,一直是一条小溪,特别有趣味和挑战。
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK