我实例化一个 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();
这篇关于清除向量会影响其容量吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!
fpermissive 标志有什么作用?What does the fpermissive flag do?(fpermissive 标志有什么作用?)
如何在我不想编辑的第 3 方代码中禁用来自 gccHow do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?(如何在我不想编辑的第 3 方代码中禁
使用 GCC 预编译头文件Precompiled headers with GCC(使用 GCC 预编译头文件)
如何在 OS X 中包含 omp.h?How to include omp.h in OS X?(如何在 OS X 中包含 omp.h?)
如何让 GCC 将 .text 部分编译为可写在 ELF 二进制文How can I make GCC compile the .text section as writable in an ELF binary?(如何让 GCC 将 .text 部分编译为可写在 ELF 二进制文件中?)
GCC、字符串化和内联 GLSL?GCC, stringification, and inline GLSL?(GCC、字符串化和内联 GLSL?)