Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

map/set iterator not incrementablemap/set iterator not incrementable

Tags:

c++

visual-c++

Driver::~Driver()
{
    AutoCritSec acsDriverList(m_csDriverList,true);
    DRIVERLIST::iterator it = m_DriverList.begin();
    for(;it!=m_DriverList.end();it++) 
    {
        if (it->second == this) 
        {
            m_DriverList.erase(it);
            it = m_DriverList.begin();
        }
    }
}

When I compile my program in visual studio 2003, my program behaves well and good. but when i do the same in 2010, then while closing the application i get some error like

Expression:map/set iterator not incrementable

and when i press to ignore this i get

Expression:"standard c++ library out of range" && 0

Does any one has any idea what is going on here: I will extremely indebted for any suggestions by anyone. Tons of thanks and warm wishes.

like image 656
user1107855 Avatar asked Jan 25 '12 03:01

user1107855


2 Answers

If this is the only element in the list, you will overrun the end of the list.

After you remove this from the list, you reset it = m_DriverList.begin();. This is fine. Then the loop expression is evaluated (the i++ from the for statement), which causes it to be advanced past the end of the range.

Advancing an iterator past the end of the container causes the program to exhibit undefined behavior. Recent versions of Visual C++ helpfully detect many common iterator errors in debug builds of your program and raise assertions to help you to solve them.

You can resolve the problem by removing loop expression and moving it into an else statement:

while (it != m_DriverList.end())
{
    if (it->second == this)
    {
        m_DriverList.erase(it);
        it = m_DriverList.begin();
    }
    else
    {
        ++it;
    }
}

Though, restarting iteration every time you remove an element is rather wasteful. Consider instead using using the iterator returned by the call to erase:

it = m_DriverList.erase(it);
like image 135
James McNellis Avatar answered Oct 14 '22 21:10

James McNellis


The correct erase idiom for associative containers is as follows:

for (auto it = container.begin(); it != container.end() /* not hoisted */; /* no inc. */ )
{
    if (delete_condition)
    {
        container.erase(it++);
    }
    else
    {
        ++it;
    }
}
like image 29
Kerrek SB Avatar answered Oct 14 '22 22:10

Kerrek SB