矢量的清晰vs设置 [英] vector's clear vs setsize

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

问题描述

我在网络上阅读,在一个严格的循环中,如果你重复地清除你的向量,最好使用resize(0),因为它可能更快。我不知道这个。

I read on the net someplace that in a tight loop if you are clearing your vector repetitively, it might be better to use resize(0) as it might be faster. I am not sure about this. Anyone's got a definitive answer to this?

推荐答案

我假设你的意思是 resize c $ c>而不是 setsize ,并调用而不是 clear() std :: vector 。 IIRC最近的回答讨论了这个(找不到链接),并且在现代STL实现上, clear()可能等同于 resize )

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.

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

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