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

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

问题描述

我实例化一个 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>().swap(foo);

在 C++11 标准中,你可以更明确地做到这一点:

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

foo.shrink_to_fit();

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

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