title: Memory consumption by STL containers
body: <p>I am working on an application in which I am planning to use couple of STL containers. The application will take certain steps if memory consumption reaches a threshold. For that purpose I need to perform a close to accurate calculation on how much memory is used by STL containers.</p>
  
  <pre><code>vector&lt;string&gt; StringList
  map&lt;string, int&gt; mapstring
  </code></pre>
  
  <p>This is how I am estimating memory:</p>
  
  <p>For size of <code>StringList</code>, loop over all the elements of the vector and keep adding the string sizes.</p>
  
  <pre><code>string size = sizeof(string) + string.capacity()*sizeof(char)
  </code></pre>
  
  <p>Then finally add to this <code>sizeof(StringList);</code></p>
  
  <p>For size of mapstring, loop over all the keys of the container and keep adding the string sizes and then add the sizes of int which is <code>mapstring.size()*sizeof(int)</code>. Then finally add to this <code>sizeof(mapstring);</code></p>
  
  <p>I guess a better approach would be specifying own allocator class and keeping track of memory usage inside it but writing one could be non-trivial. Does this estimation look good ?</p>