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
sizeofoperator is always evaluated at compile time, so everyvector<T>will have the same size (unlessvector<T>is a specialization likevector<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:
This is only an approximation because it does not take into account book-keeping data on the heap.