Note that there are some explanatory texts on larger screens.

plurals
  1. POpossible inconsistency in std::vector while erasing an element
    primarykey
    data
    text
    <p>while debugging a vector, I see an inconsistency. Assume the following code which tries to remove an entry from a vector which has only one element</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; std::vector&lt;int&gt; v; void myremove(int); int main() { v.push_back(10); std::cout &lt;&lt; "10 pushed back\n"; myremove(10); std::cout &lt;&lt; "done :)\n"; return 0; } void myremove( int a ) { std::vector&lt;int&gt;::iterator it = v.begin(); int counter = 0; for ( ; it != v.end(); it++ ) { std::cout &lt;&lt; "iterating for " &lt;&lt; counter &lt;&lt; " times and vector size is " &lt;&lt; v.size() &lt;&lt; "\n"; if ( a == (*it) ) { v.erase(it); std::cout &lt;&lt; "removed " &lt;&lt; a &lt;&lt; "\n"; } ++counter; } } </code></pre> <p>This is what I see in the output:</p> <pre><code> $ g++ test.cpp $ ./a.out | more 10 pushed back iterating for 0 times and vector size is 1 removed 10 iterating for 1 times and vector size is 0 iterating for 2 times and vector size is 0 iterating for 3 times and vector size is 0 iterating for 4 times and vector size is 0 iterating for 5 times and vector size is 0 iterating for 6 times and vector size is 0 .... .... iterating for 33790 times and vector size is 0 Segmentation fault </code></pre> <p>What I understand is that when the element is removed the size will become 0, however the iterator moves one step and still it tries to reach the end but he doesn't know that he has already passed the end point.</p> <p>Can someone explain more what is going on and how to avoid that?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload