矢量清晰与调整大小 [英] Vector clear vs. resize

查看:92
本文介绍了矢量清晰与调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在互联网上读到,如果反复(紧密循环)清除 std :: vector ,最好使用 resize(0)而不是 clear(),因为它可能更快.我对此不太确定.有人对此有明确的答案吗?

I read on the Internet that if you are clearing a std::vector repetitively (in a tight loop), it might be better to use resize(0) instead of clear(), as it may be faster. I am not sure about this. Does anyone have a definitive answer to this?

推荐答案

我假设您的意思是 resize(0)而不是 setsize ,然后调用它而不是> clear(),而您正在谈论的是 std :: vector .IIRC的最新答案对此进行了讨论(找不到链接),并且在现代STL实现中, clear()可能与 resize(0)相同.

I assume you mean resize(0) instead of setsize, and calling that instead of clear(), and that you're talking about std::vector. IIRC a recent answer discussed this (can't find the link), and on modern STL implementations, clear() is likely identical to resize(0).

以前清除向量可能会释放其所有内存(即,其容量也将降为零),从而在您再次开始添加元素时导致重新分配,这与 resize(0)保持容量相反因此重新分配较少.但是,我认为在现代STL库中没有区别.如果您使用的是旧的STL实现,或者只是偏执, resize(0)可能会更快.

Previously clearing a vector might have freed all its memory (ie. its capacity also falls to zero), causing reallocations when you start adding elements again, in contrast to resize(0) keeping the capacity so there are fewer reallocations. However, I think in modern STL libraries there is no difference. If you're using an old STL implementation, or you're just paranoid, resize(0) might be faster.

这篇关于矢量清晰与调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆