Reputation: 2330
Why can't I edit a set/map while iterating on it? Example:
bool flag;
set <int> :: iterator aIterator;
set <int> :: iterator bIterator;
bIterator = B.begin();
for (bIterator=B.begin(); bIterator!=B.end(); ++bIterator)
{
flag = true;
aIterator = A.begin();
for (aIterator=A.begin(); aIterator!=A.end(); ++aIterator)
{
if (*bIterator == *aIterator)// if an elemnet in B is found in A, delete that element from A and check the next element of B
{
A.erase(aIterator);
flag = false;
break;
}
}
if (flag == true)
A.insert(*bIterator); //if not found then add that element to A(which now represents the set of symmetric difference)
}
and how can I handle that? I mean, how can I edit a set while iterating?
Upvotes: 0
Views: 58
Reputation: 13952
Do this:
for (aIterator=A.begin(); aIterator!=A.end(); ++aIterator)
not that:
for (bIterator=A.begin(); bIterator!=A.end(); ++aIterator)
aIterator is not intialized, you can't increment it.
The rest of it looks ok.
Upvotes: 1