map/set iterator not incrementablemap/set iterator not incrementable

走远了吗. 提交于 2020-01-12 04:29:33

问题


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.


回答1:


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);



回答2:


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;
    }
}


来源:https://stackoverflow.com/questions/8997503/map-set-iterator-not-incrementablemap-set-iterator-not-incrementable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!