title: Why is the iterator to the last element of the vector holding a corrupted value? (refer code)
body: <p>The below code throws heap-use-after-free error.</p>
  
  <pre><code>#include &lt;iostream&gt;
  
  int main()
  {
      unordered_map&lt;int, vector&lt;int&gt;::iterator&gt; mp;
      vector&lt;int&gt; num;
  
      auto insert = [&amp;](int n)
      {
          if (mp.count(n) != 0)
              return false;
  
          num.push_back(n);
          mp[n] = prev(num.end());
          return true;    
      };
  
      insert(1);
      insert(2);
      insert(3);
  
      for (auto n : num)
          cout &lt;&lt; n &lt;&lt; endl;
  
      cout &lt;&lt; endl;
  
      for (auto m : mp)
      {
          cout &lt;&lt; m.first &lt;&lt; " -&gt; ";
          cout &lt;&lt; distance(num.begin(), m.second) &lt;&lt; endl; 
          // cout &lt;&lt; *m.second &lt;&lt; endl;
      }
  
      return 0;
  }
  </code></pre>
  
  <p>The output of the above code is</p>
  
  <pre><code>1
  2
  3
  
  3 -&gt; 2
  1 -&gt; -16
  2 -&gt; -7
  </code></pre>
  
  <p>It obviously crashes if I try to access <code>*m.second</code>.
  Why are the iterator values seemingly corrupted here?</p>
  
  <p>I have tried replacing vector with list and the above code works fine. I wonder if this has something to do with how vector expands on "push_back" maybe. I have tried other ways to get the iterator to the last element of the vector with indifferent results.</p>