3

std::vector 的 reserve, resize, clear, shrink_to_fit 的内存逻辑

 2 years ago
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 的内存逻辑

作者: 张志强

, 发表于 2021-08-27

, 共 330 字 , 共阅读 13 次

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.

avatar-0.jpg
这个路线和之前的10 公里大环线类似,水库沿山脊的路线因为植被过于茂密,以及有很多蜘蛛网,改成从水库直接上快活林。因此路程稍微短了一些。但这段路也很有意思,一直是一条小溪,特别有趣味和挑战。

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK