调用 std::vector::clear() 会将 std::vector::capacity() 设置为零吗?

发布于 2024-08-28 15:27:03 字数 114 浏览 3 评论 0原文

如果我在向量上使用 .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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

终止放荡 2024-09-04 15:27:03

指定 std::vector::clear() 影响大小。可能不会影响容量。要重置容量,请使用交换技巧

    std::vector<int> v1;

    // somehow increase capacity

    std::vector<int>().swap(v1);

注意:由于这个旧答案仍在获得支持(因此人们会阅读它),我觉得需要补充的是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:

    std::vector<int> v1;

    // somehow increase capacity

    std::vector<int>().swap(v1);

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.

爱的故事 2024-09-04 15:27:03

尽管我认为标准中没有指定该行为,但它可能不会释放保留的内存。

编辑:好吧,刚刚检查过,标准只说后置条件是 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 a vector implementation that doesn't hold on to the reserved memory.

2024-09-04 15:27:03

不,不会。通过调用 vector::capacity() 进行尝试。

shr​​ink_to_fit 的出现进一步证明了这一点。该标准的工作草案提到:

备注:
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:

Remarks:
shrink_to_fit is a non-binding request
to reduce capacity() to size(). [
Note: The request is non-binding to
allow latitude for
implementation-specific optimizations
.
—end note ]

萝莉病 2024-09-04 15:27:03

不,它不会将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.

土豪 2024-09-04 15:27:03

它不会影响底层缓冲区大小。这就是为什么你必须使用像 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文