Size of vector of vector c++
c++, memory, sizeof, vector
Solution
In your second case, every single of your `n * m` elements is a `vector<int>`, which has to be dynamically allocated. Each such dynamic allocation has an overhead. It is not unusual to find dynamic allocations having a 32-64 byte overhead. This is highly likely part of the reason for your "missing" bytes.
Problem
I'm trying to estimate the size in memory of a vector of a vector, but it seems I don't get the correct approximation. Here is the small code I wrote to check : ``` #include <vector> #include <iostream> using namespace std; int main(int argc, char** argv) { size_t n = 100; size_t m = 1000000; float sizeInKB = (sizeof(vector<vector<int> >) + n*sizeof(vector<int>) + n*m*sizeof(int))/1024.0f; cout << sizeInKB << " KB" << endl; vector<vector<int> > vect(n); for(int i = 0; i < n; ++i) { vect[i].resize(m); } while(true) {} return EXIT_SUCCESS; } ``` As output, I get 390 630 KB, whereas the application takes 394 588 KB in memory according to the task manager. I agree that this is not the best way to know how much memory is used by the application (and especially by the vector) but it gives a good hint, and 4 MB is not only a few KB. Now if I try to estimate the size in memory of a vector of vector of vector, it gets more and more messy. With the same code, replacing `int` by `vector<int>` : ``` #include <vector> #include <iostream> using namespace std; int main(int argc, char** argv) { size_t n = 100; size_t m = 1000000; float sizeInKB = (sizeof(vector<vector<vector<int> > >) + n*sizeof(vector<vector<int> >) + n*m*sizeof(vector<int>))/1024.0f; cout << sizeInKB << " KB" << endl; vector<vector<vector<int> > > vect(n); for(int i = 0; i < n; ++i) { vect[i].resize(m); } while(true) {} return EXIT_SUCCESS; } ``` As output I get 4 687 500 KB, whereas the application takes 6 271 028 KB in memory according to the task manager. There is a difference of more than 1.5 GB ... Where is this overhead coming from ? Is there a way to compute it ? I'm running all of this on Windows 7 Pro 64 bits, with Visual Studio 2008 ... Thanks in advance,