can i define an iterator inside a while loop?
<p>My code has no compilation error. It seems to have a runtime error. In the following piece of code, when the while loop is executed for the first time everything works fine. But on the second iteration, everything stops at "list::iterator k = (temp2->store).begin();". When I comment out the "list::iterator k ..." part everything works fine. The variables temp2 and temp2->store are not NULL or empty. The debugger gave the following message "Unhandled exception at 0x009bc0cf in project euler.exe: 0xC0000005: Access violation reading location 0xddddddf5".</p>

<pre><code> struct edge
{  int end1, end2;    
   ptr_to_edge *ptr_end1, *ptr_end2;
   edge *next, *l_chd, *r_chd; 
   edge(): next(NULL), l_chd(NULL), r_chd(NULL),  ptr_end1(NULL), ptr_end2(NULL)
  { }
};


   struct ptr_to_edge {
        int flag, vertex;    
        list&lt;edge*&gt; store;
        ptr_to_edge(): flag(1)
        { }
     };
 void parallel_reduction_step(ptr_to_edge *front, vector&lt;edge&gt; &amp;a) {

  list&lt;edge*&gt;::iterator next = (front-&gt;store).begin();
  next++;
  list&lt;edge*&gt;::iterator current = (front-&gt;store).begin();
  list&lt;edge*&gt;::iterator last = (front-&gt;store).end();
  --last;

  while(current!= last) {

      if(((*current)-&gt;end1 == (*next)-&gt;end1)&amp;&amp;((*current)-&gt;end2==(*next)-&gt;end2)) {

             edge temp1;
             temp1.end1 = (*current)-&gt;end1; temp1.end2 = (*current)-&gt;end2;
             a.push_back(temp1);

             ptr_to_edge *temp2;
             if ((*current)-&gt;end1==front-&gt;vertex) 
                 temp2 = (*current)-&gt;ptr_end2;
             else 
                 temp2 = (*current)-&gt;ptr_end1; 

             list&lt;edge*&gt;::iterator k = (temp2-&gt;store).begin();

              current = (front-&gt;store).erase(j);
             *current = &amp;(a.back());
             }
      else current++;
      next++;
      }
  };
</code></pre>
