了解C ++中的向量实例占用的空间 [英] Understanding the space occupied by an vector instance in C++
问题描述
我试图理解std :: vector实例占用的字节数。以下代码:
vector< int> uno;
uno.push_back(1);
uno.push_back(1);
cout<<1:< sizeof(uno)<<bytes<< endl;
cout<< endl;
vector< bool> unos;
unos.push_back(true);
cout<<2:< sizeof(unos)<<bytes<< endl;
cout<< endl;
给我这个输出:
1 :12个字节
2:20个字节
有人可以解释为什么向量< bool>
具有比向量< int>
?更多的字节。测量向量实例的大小(以字节为单位)的正确方法是...向量中添加每个成员的大小?
在C ++中, sizeof
运算符在编译时被总是评估,因此每个向量< T&
将具有相同的大小(除非向量< T>
是如向量< bool>
)。
如果你想知道12个字节,那么可能是3个指针的大小,或者指针的大小和元素数和容量。实际数据从不存储在向量
内。
如果要知道总使用了多少内存,好的近似是:
sizeof(std :: vector< T>)+ my_vector.capacity
这只是一个近似值,因为它不考虑堆上的记帐数据。 / p>
I'm trying to understand the amount of bytes occupied by an instance of std::vector. The following code:
vector <int>uno;
uno.push_back(1);
uno.push_back(1);
cout <<"1: "<< sizeof(uno)<<" bytes"<<endl;
cout << endl;
vector <bool>unos;
unos.push_back(true);
cout <<"2: "<< sizeof(unos)<<" bytes"<<endl;
cout << endl;
gives me this output:
1: 12 bytes
2: 20 bytes
Can someone explain me why the size of the vector<bool>
has more bytes than the vector<int>
?. And what is the correct way to measure the size in bytes of an vector instance... by adding the size of every member in the vector?
In C++, the sizeof
operator is always evaluated at compile time, so every vector<T>
will have the same size (unless vector<T>
is a specialization like vector<bool>
).
In case you are wondering about the 12 bytes, that is probably the size of 3 pointers, or alternatively, the size of a pointer and an element count and a capacity. The real data is never stored inside the vector
.
If you want to know how much memory is used total, a good approximation is:
sizeof(std::vector<T>) + my_vector.capacity() * sizeof(T)
This is only an approximation because it does not take into account book-keeping data on the heap.
这篇关于了解C ++中的向量实例占用的空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!