c++ How to erase object using vector with auto while inside loop
<p>Hi folks at stackoverflow,</p>

<p>I've been wondering if there were any easy means for: <strong>iterator controlled ranged for-loops</strong> to properly erase objects from within its containers while accessing it; using auto it.</p>

<p>For a standard indexed controlled for-loop, I would do something like this:</p>

<pre><code>void del(int i){
    cout&lt;&lt;"Deleting: "&lt;&lt;myObjects[i]&lt;&lt;':'&lt;&lt;myObjects[i]-&gt;c&lt;&lt;endl;
    for(unsigned int j = 0; j &lt; allObjects.size();){
        if(allObjects[j] == myObjects[i]){
            delete allObjects[j];
            allObjects[j] = 0;
            allObjects.erase(allObjects.begin()+j);
            break;//Found and deleted first instance, escaping for-loop.
        }else{
            ++j;
        }
    }
    myObjects[i]=0;
    myObjects.erase(myObjects.begin()+i);
}
</code></pre>

<p>An auto for loop would look something like this:</p>

<pre><code>void del(int i){
    cout&lt;&lt;myObjects[i]&lt;&lt;endl;
    for(auto it: allObjects)
        if(it == myObjects[i]){
            delete it;
            it = 0;
            //allObjects.erase();// Found, needs erasing.
        }
    myObjects[i]=0;
    myObjects.erase(myObjects.begin()+i);
}
</code></pre>

<p>I haven't been able to properly work this out and have been resorting to old school indexing(many ways to do it with an index).</p>

<p>I can delete it, and set it to 0, but how would I also erase it from the vector and possibly while in the vector without knowing an index? I know I can keep track of the loop and do so using a counter, but that would defeat the purpose of using a nice clean iterator loop.</p>

<p>If not to be removed in the vector, how would I go about so afterwards in an easily manner other than re-accessing the vector?</p>

<p>Nothing wrong with using index driven for-loops, just wanted to know if there was an easy alternative using our new friend "auto it".</p>

<p>Thanks.</p>