A_Matar
A_Matar

Reputation: 2330

Sets/Maps iterators not incrementable

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

Answers (1)

0x26res
0x26res

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

Related Questions