loop for and std::list iterator

R

raven.mp4

Hi,
I have a little question about std::list iterators. Take a look at
this piece of code:

list<Type*>::iterator it = myList.begin();

Type *p;

for(it; it != myList.end(); ++it)
{
p = (*it);

if(...)
{
myList.pop_front();
InsertIntoList(p); // inserts p into new location
it = myList.begin();
}
else
break;
}

Why 'it = myList.begin()' doesn't set 'it' to the beginning of the
myList?
 
M

Markus Schoder

Hi,
I have a little question about std::list iterators. Take a look at this
piece of code:

list<Type*>::iterator it = myList.begin();

Type *p;

for(it; it != myList.end(); ++it)
{
p = (*it);

if(...)
{
myList.pop_front();
InsertIntoList(p); // inserts p into new location
it = myList.begin();
}
else
break;
}

Why 'it = myList.begin()' doesn't set 'it' to the beginning of the
myList?

It does. Then "it" gets incremented (possibly invoking undefined
behaviour if the list is empty) and then the next loop iteration begins
with "it" pointing to the second element in the list.

It is difficult to tell but it almost looks like you rather wanted

while(!myList.empty())
{
it = myList.begin();
p = *it;

if(...)
{
myList.pop_front();
InsertIntoList(p); // inserts p into new location
}
else
break;
}
 
R

raven.mp4

It does. Then "it" gets incremented (possibly invoking undefined
behaviour if the list is empty) and then the next loop iteration begins
with "it" pointing to the second element in the list.

It is difficult to tell but it almost looks like you rather wanted

while(!myList.empty())
{
it = myList.begin();
p = *it;

if(...)
{
myList.pop_front();
InsertIntoList(p); // inserts p into new location
}
else
break;

}

Oh, now I see my mistake. Thank you for explanation.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,150
Members
46,697
Latest member
AugustNabo

Latest Threads

Top