Problem in erasing element in list
struct ScheduleTaskInfo
{
unsigned int nTaskID;
__time64_t timeStartTime;
__time64_t timeEndTime;
};
typedef list<ScheduleTaskInfo> SchedulerList;
SchedulerList::iterator itrSchedulerList;
for(itrSchedulerList = gSchedulerList.begin();itrSchedulerList != gSchedulerList.end();itrSchedulerList++)
{
SYSTEMTIME st;
GetLocalTime(&st);
CTime ctSyatemTime(st);
if (itrSchedulerList->timeEndTime == ctSyatemTime.GetTime())
{
itrSchedulerList = gSchedulerList.erase(itrSchedulerList);
}
}
I am doing this it is crashing in for loop.I think it i开发者_运维技巧s due to erase(); Am I doing something wrong here??Please suggest me on this
You should write itrSchedulerList++
in else-block
as:
for(itrSchedulerList = gSchedulerList.begin();
itrSchedulerList !=gSchedulerList.end();)
{
SYSTEMTIME st;
GetLocalTime(&st);
CTime ctSyatemTime(st);
if (itrSchedulerList->timeEndTime == ctSyatemTime.GetTime())
{
itrSchedulerList = gSchedulerList.erase(itrSchedulerList);
}
else
itrSchedulerList++;
}
This ensures that you don't increment it beyond end of the list. erase()
might return end iterator which will be incremented in the for
loop in your version.
You shall not increment the iterator when you reassign it to the return of erase
, as you'll effectively skip one element. Put it in an extra else
block:
if (itrSchedulerList->timeEndTime == ctSyatemTime.GetTime())
{
itrSchedulerList = gSchedulerList.erase(itrSchedulerList);
}
else
{
++itrSchedulerList;
}
And take it out of the for-loop.
精彩评论