title: What is the most efficient way to initialize a 3D vector?
body: <p>I have a 3D string vector in C++:</p>
  
  <pre><code>vector&lt;vector&lt;vector&lt;string&gt;&gt;&gt; some_vector
  </code></pre>
  
  <p>That I am trying is to find a fast method to allocate memory for it.</p>
  
  <p>I tried to define it with two different methods as follow:</p>
  
  <pre><code>#include&lt;vector&gt;
  #include&lt;iostream&gt;
  #include&lt;ctime&gt;
  using namespace std;
  
  #define DIM1 100
  #define DIM2 9
  #define DIM3 120
  
  int main()
  {
      clock_t t1_start = clock();
      vector&lt;vector&lt;vector&lt;string&gt;&gt;&gt; vec1(DIM1, vector&lt;vector&lt;string&gt;&gt;(DIM2, vector&lt;string&gt;(DIM3)));
      clock_t t1_end = clock();
      double diff1 = (t1_end - t1_start) / double(CLOCKS_PER_SEC);
  
      clock_t t2_start = clock();
      vector&lt;vector&lt;vector&lt;string&gt;&gt;&gt; vec2;
      vec2.resize(DIM1);
      for(int i = 0; i &lt; DIM1; i++)
      {
          vec2[i].resize(DIM2);
          for(int j = 0; j &lt; DIM2; j++)
              vec2[i][j].resize(DIM3);
      }
      clock_t t2_end = clock();
  
      double diff2 = (t2_end - t2_start) / double(CLOCKS_PER_SEC);
  
      cout&lt;&lt;"1st definition used time: "&lt;&lt;diff1&lt;&lt;"s"&lt;&lt;endl;
      cout&lt;&lt;"2nd definition used time: "&lt;&lt;diff2&lt;&lt;"s"&lt;&lt;endl;
  }
  </code></pre>
  
  <p>I expect that the first method (vec1) could be faster than the 2nd one (vec2). </p>
  
  <p>But it turned out that the 1st method is much slower than the 2nd. On my machine, the 1st method used 0.245 seconds, while the 2nd method used 0.152 seconds. </p>
  
  <p>Moreover, when I switch the data type to int, the 1st one took 0.058 second, and the 2nd took 0.004.</p>
  
  <p>May I know what cause such difference? And is there better way to allocate memory for a 3D vector?</p>
  
  <p>Many thanks in advance.</p>