question about <list> and pointer to its items

L

lallous

Hello

Given this:

list<mystruct_t> lst;

lst.push_back(item1);
lst.push_back(item2);
lst.push_back(item3);

Now say I have this:

mystruct_t *p1, *p2, *p3 pointing to item1->item3 memory in side the list.

If I delete "item2" (or second item) will the other pointers still be valid?
 
J

John Harrison

lallous said:
Hello

Given this:

list<mystruct_t> lst;

lst.push_back(item1);
lst.push_back(item2);
lst.push_back(item3);

Now say I have this:

mystruct_t *p1, *p2, *p3 pointing to item1->item3 memory in side the list.

If I delete "item2" (or second item) will the other pointers still be valid?

If you use iterators instead of pointers (like you should) then the C++
standard guarantees that the iterators will remain valid. I don't know that
the standard guarantees that pointers will be OK, but its very likely to
work.

John
 
L

lallous

John Harrison said:
If you use iterators instead of pointers (like you should) then the C++
standard guarantees that the iterators will remain valid. I don't know
that
the standard guarantees that pointers will be OK, but its very likely to
work.

You mean I change p1, p2, p3 to:
list<mystruct_t>::iterator p1, p2, p3;

then have p1, p2, p3 point to each element, then when any element is deleted
the other iterators are still valid?
 
S

Sharad Kala

John Harrison said:
If you use iterators instead of pointers (like you should) then the C++
standard guarantees that the iterators will remain valid.

I think Standard only talks of iterators and references remaining valid, and
am too lazy to check the Standard :)

Sharad
 
J

John Harrison

lallous said:
You mean I change p1, p2, p3 to:
list<mystruct_t>::iterator p1, p2, p3;

then have p1, p2, p3 point to each element, then when any element is deleted
the other iterators are still valid?

Yes.

john
 

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
474,178
Messages
2,570,955
Members
47,509
Latest member
Jack116

Latest Threads

Top