Checking if iterator points to a specific element

M

Martin Magnusson

Hi

I'm traversing a std::list backwards with a reverse_iterator, and need
to check for the case when the iterator points to the first element of
the list.

My code now looks something like the code posted below. This usually
works a few times, but then gives me a segmentation fault, apparently at
the line "if (pos == --(the_list.rend()))". Shouldn't that always be
valid, as long as there is always at least one element in the list at
the beginning of the loop? Is there a better way to check if the
iterator points to the first list element?

list<MyClass*>::reverse_iterator i;
for (pos = the_list.rbgin(); pos != the_list.rend(); /**/ )
{
if (pos == --(the_list.rend())) /* Is this not always valid? */
{
// Do something with *pos
the_list.clear();
pos = the_list.rend();
}
else
{
// Do something else with *pos
++pos;
the_list.erase( pos.base(), the_list.end() );
pos = the_list.rbegin();
}
}
 
V

Victor Bazarov

Martin Magnusson said:
I'm traversing a std::list backwards with a reverse_iterator, and need
to check for the case when the iterator points to the first element of
the list.

My code now looks something like the code posted below. This usually
works a few times, but then gives me a segmentation fault, apparently at
the line "if (pos == --(the_list.rend()))". Shouldn't that always be
valid, as long as there is always at least one element in the list at
the beginning of the loop?

'rend' returns a temporary. -- expects a modifiable lvalue. Could that
be the source of the problem?
Is there a better way to check if the
iterator points to the first list element?

'front' returns a reference to the first element, or you could do

list<MyClass*>::reverse_iterator one_before_rend = the_list.rend();
--one_before_rend;

and compare with 'one_before_rend' instead of that expression.
 
M

Martin Magnusson

Victor said:
'front' returns a reference to the first element, or you could do

list<MyClass*>::reverse_iterator one_before_rend = the_list.rend();
--one_before_rend;

and compare with 'one_before_rend' instead of that expression.

Thanks! Comparing *pos with the_list.front() did the trick! Using the
soltion with one_before_end still gave me sporadic segmentaition faults
though.
 

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

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top