清除矢量会影响其容量吗? [英] Does clearing a vector affect its capacity?

查看:153
本文介绍了清除矢量会影响其容量吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我实例化 std :: vector foo(1000)

foo .size()现在是1000, foo.capacity()也是1000。

foo.size() is now 1000 and foo.capacity() is also 1000.

如果我用 foo.clear()清除向量, size()现在是0,是 capacity()?标准是否说明了这一点?

If I clear the vector with foo.clear(), the size() is now 0, but what is the capacity()? Does the standard say anything about that?

推荐答案

不,不是。矢量的容量从不减小。这不是标准强制的,但是在VC ++和g ++的标准库实现中都是如此。为了将容量设置为适合大小,使用着名的交换技巧

No, it doesn't. The capacity of a vector never decreases. That isn't mandated by the standard but it's so both in standard library implementations of VC++ and g++. In order to set the capacity just enough to fit the size, use the famous swap trick

vector<T>(foo).swap(foo);

在C ++ 11 stantard中,您可以更明确地执行:

In C++11 stantard, you can do it more explicitly:

foo.shrink_to_fit();

这篇关于清除矢量会影响其容量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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