Initial capacity of vector in C++(C++中向量的初始容量)
问题描述
使用默认构造函数创建的 std::vector 的 capacity() 是多少?我知道 size() 为零.我们可以声明默认构造的向量不会调用堆内存分配吗?
What is the capacity() of an std::vector which is created using the default constuctor? I know that the size() is zero. Can we state that a default constructed vector does not call heap memory allocation?
通过这种方式,可以使用单个分配创建具有任意保留的数组,例如 std::vector.假设出于某种原因,我不想在 2345 上启动 size().
This way it would be possible to create an array with an arbitrary reserve using a single allocation, like std::vector<int> iv; iv.reserve(2345);. Let's say that for some reason, I do not want to start the size() on 2345.
例如,在 Linux(g++ 4.4.5,内核 2.6.32 amd64)上
For example, on Linux (g++ 4.4.5, kernel 2.6.32 amd64)
#include <iostream>
#include <vector>
int main()
{
using namespace std;
cout << vector<int>().capacity() << "," << vector<int>(10).capacity() << endl;
return 0;
}
打印0,10.这是规则,还是取决于 STL 供应商?
printed 0,10. Is it a rule, or is it STL vendor dependent?
推荐答案
该标准没有指定容器的初始 capacity 应该是多少,因此您依赖于实现.一个常见的实现将从零开始容量,但不能保证.另一方面,没有办法改善 std::vector 所以坚持下去.
The standard doesn't specify what the initial capacity of a container should be, so you're relying on the implementation. A common implementation will start the capacity at zero, but there's no guarantee. On the other hand there's no way to better your strategy of std::vector<int> iv; iv.reserve(2345); so stick with it.
这篇关于C++中向量的初始容量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++中向量的初始容量
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
