how to erase a list member with just an iterator (without the list itself)?

A

alon

I got the following situation: I have a few lists of integers, and I
have an iterator pointing to one of the elements. I don't have a
pointer to the list itself ! All I want is to remove the element the
iterator points to...

Basically, a list element has pointers back and forth, so I shouldn't
need the list itself, but I don't see any function that does the work.
Is there a real problem to do this? Is it just a coincidence that no
body implemented such a function?
 
A

alon

I'll try and clarify my question:

The erase function requires a pointer to the list.
list<int> L;
list<int>::iterator iter;
L.erase(iter);

In my case there is no pointer to the list, so what I need is something
like this:
list<int>::erase(iter);

Does this clarify my question?
 
R

red floyd

alon said:
I'll try and clarify my question:

The erase function requires a pointer to the list.

No, erase is a member function of the list, and therefore requires a
list object.
list<int> L;
list<int>::iterator iter;
L.erase(iter);

In my case there is no pointer to the list, so what I need is something
like this:
list<int>::erase(iter);


Nope. How does erase know what list to erase from? Again, erase is a
*MEMBER FUNCTION* and therefore requires the object.
 
D

Daniel T.

alon said:
I got the following situation: I have a few lists of integers, and I
have an iterator pointing to one of the elements. I don't have a
pointer to the list itself ! All I want is to remove the element the
iterator points to...

Basically, a list element has pointers back and forth, so I shouldn't
need the list itself, but I don't see any function that does the work.
Is there a real problem to do this? Is it just a coincidence that no
body implemented such a function?

It cannot be done, and that was by design. Removing an element from a
list without notifying the list is poor practice and makes some list
optimizations difficult to implement. For example, a list may contain a
"size_" member variable in order to speed up the call to myList.size().
Removing a element without telling the list would corrupt that member.

Of course, if each list iterator had a pointer to the list it belonged
too, then it could be done, but the C++ committee apparently decided not
to do that.
 
A

alon

"if each list iterator had a pointer to the list " - in practice, this
is what I ended up doing :)

Thx,
Alon
 

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,767
Messages
2,569,572
Members
45,045
Latest member
DRCM

Latest Threads

Top