title: Adding vector to 2D vector, and keeping reference to the last vector
body: <p>I am writing a program and there was a very subtle error that was hard to recognize.</p>
  
  <p>I examined the program for hours and it looks like it's from my misuse of <code>resize()</code> in allocating a new <code>vector</code> in 2D <code>vector</code>, from my misuse of <code>back()</code> in <code>vector</code>, or from updating a reference variable.</p>
  
  <p>I wrote a simpler code that contains similar problem in my original program for demonstration:</p>
  
  <pre><code>int main() {
  
      vector&lt;vector&lt;int&gt;&gt; A(1);
      vector&lt;int&gt; &amp;recent = A.back();
  
      recent.emplace_back(50);
      cout &lt;&lt; A.back()[0] &lt;&lt; endl; //prints 50
  
      A.resize(2);
      A[1] = vector&lt;int&gt;();
      cout &lt;&lt; A.size() &lt;&lt; endl;    //prints 2
      recent = A.back();
      cout &lt;&lt; A[1].size() &lt;&lt; endl; //prints 0
      recent.emplace_back(20);     //Segmentation fault occurs!!
      cout &lt;&lt; A[1][0] &lt;&lt; endl;
  }
  </code></pre>
  
  <p>Segmentation fault occurs when I tried to <code>emplace_back(20)</code>, although in my original program it doesn't throw any error and doesn't <code>emplace</code> the element either.</p>
  
  <p>Possible cause of problem, in my opinion is:</p>
  
  <ol>
  <li>I used <code>resize()</code> to allocate a new <code>vector</code> after the current last position of the 2D vector <code>A</code>, because I didn't know how to <code>emplace_back()</code> an empty vector.</li>
  </ol>
  
  <p>2, 3. In <code>recent = A.back();</code>, I'm not sure if I am updating the reference variable(defined as <code>vector&lt;int&gt; &amp;recent</code>) correctly, and if <code>back()</code> gives the correct reference to the newly allocated vector at the end of the 2D vector <code>A</code>.</p>
  
  <p>The logic looked perfectly fine, but obviously I am doing something wrong.</p>
  
  <p>What am I doing wrong, and what can I do instead?</p>