清除向量会影响其容量吗?

2021-12-21 00:00:00 size vector c++ capacity std

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

相关文章