문제

I got a code like this:

for (set<GROUP*>::iterator i = Data.m_Resulting.begin(); i != Data.m_Resulting.end();)
{
    printf("Deleting %d\n", (*i)->nId);
    Data.m_MpptPool.erase(i++);
}

printf("Remains in pool: %d\n", Data.m_MpptPool.size());

// Dump Pool:

for (set<GROUP*>::iterator i = Data.m_MpptPool.begin(); i != Data.m_MpptPool.end(); i++)
{
    printf("\t %d\n", (*i)->nId);
}

If before deleting there was 2 objects in the set , and the firs loop deletes one of them the .size() function shows a correct number (1) However, the second for-loop that prints the contents of my set shows both elements in there. Later, referring to this element causes segmentation fault. What can be the problem here?

도움이 되었습니까?

해결책

You can not use an iterator from one std::set (m_Resulting) on another std::set (m_MpptPool). This is undefined behaviour, you need to use the value:

Data.m_MpptPool.erase(*it++);

다른 팁

Your first cycle iterates over Data.m_Resulting, but deletes elements in Data.m_MpptPool. It uses an iterator that points into the former to delete elements in the latter. That's illegal and, frankly, quite meaningless. The behavior of your code is undefined. How did you expect it to work? What did you mean by

Data.m_MpptPool.erase(i++);

when iterator i actually pointed into Data.m_Resulting?

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top