Hi folks at stackoverflow,
I've been wondering if there were any easy means for: iterator controlled ranged for-loops to properly erase objects from within its containers while accessing it; using auto it.
For a standard indexed controlled for-loop, I would do something like this:
void del(int i){
cout<<"Deleting: "<<myObjects[i]<<':'<<myObjects[i]->c<<endl;
for(unsigned int j = 0; j < 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);
}
An auto for loop would look something like this:
void del(int i){
cout<<myObjects[i]<<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);
}
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).
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.
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?
Nothing wrong with using index driven for-loops, just wanted to know if there was an easy alternative using our new friend "auto it".
Thanks.