调用 std::vector::clear() 会将 std::vector::capacity() 设置为零吗?
如果我在向量上使用 .reserve(items) ,该向量将为我猜测所需的项目数量分配足够的内存。
如果我稍后使用 .clear(),这会清除向量还是保存我之前定义的保留?
谢谢。
If I use .reserve(items) on a vector, the vector will allocate enough memory for my guess of the number of items that I'll need.
If I later on use .clear(), will that just clear the vector or save my earlier defined reserve?
thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
指定
std::vector::clear()
影响大小。可能不会影响容量。要重置容量,请使用交换技巧:注意:由于这个旧答案仍在获得支持(因此人们会阅读它),我觉得需要补充的是C++11添加了
std::vector<...>::shrink_to_fit()
,它要求用于删除未使用容量的向量。It is specified that
std::vector<T>::clear()
affects the size. It might not affect the capacity. For resetting the capacity, use the swap trick:Note: Since this old answer is still getting upvotes (thus people read it), I feel the need to add that C++11 has added
std::vector<...>::shrink_to_fit()
, which requests the vector to remove unused capacity.尽管我认为标准中没有指定该行为,但它可能不会释放保留的内存。
编辑:好吧,刚刚检查过,标准只说后置条件是
size() == 0
尽管我还没有遇到向量
实现不保留保留的内存。It will probably not release the reserved memory although I don't think the behaviour is specified in the standard.
EDIT: Ok, just checked and the standard only says that the post-condition is that
size() == 0
although I haven't come across avector
implementation that doesn't hold on to the reserved memory.不,不会。通过调用
vector::capacity()
进行尝试。shrink_to_fit
的出现进一步证明了这一点。该标准的工作草案提到:No it won't. Try it out by calling
vector::capacity()
.Further evidence of this is the appearance of
shrink_to_fit
. The standard's working draft mentions:不,它不会将reserve()设置为0。调用clear()会调用每个元素的析构函数并将它们从向量中删除,使容器的大小为0,但容量保持不变。
No, it won't set reserve() to 0. Calling clear() calls the destructors of each element and removes them from the vector, leaving the container with size of 0, but the capacity remains unchanged.
它不会影响底层缓冲区大小。这就是为什么你必须使用像 this 这样的技巧来真正摆脱缓冲区或让它变小。
It will not affect the underlying buffer size. Which is why you have to use tricks like this to actually get rid of the buffer or make it smaller.