I ran into a problem where I wanted to go through my vector and delete the elements which were no longer wanted. The reason for why it failed is obvious, but I didn't see it when I tried my naive approach. Basically the iterator gets invalidated when I erase an element, and the loop can't continue. What I did is the following:
#define GOOD 1
#define BAD 0
struct Element
{
Element(int isGood) : good(isGood){}
bool good;
};
int main()
{
std::vector<Element> arr;
arr.push_back(Element(BAD));
arr.push_back(Element(GOOD));
arr.push_back(Element(BAD));
arr.push_back(Element(GOOD));
//__CLEAN ARRAY__//
for (auto it = arr.begin(); it != arr.end(); ++it)
{
if ((*it).good == false) arr.erase(it);
}
}
So it's obvious that this won't work, I was wondering what the correct/best way of doing this is. My next step would be to restart the loop with fresh iterators if there is a no good found, but this also seems like a waste. Ideally the loop would continue where it left off with fresh iterators?
Thanks.