Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove item from a list using its pointer

I have a pointer p (not an iterator) to an item in a list. Can I then use p to delete (erase) the item from the list? Something like:

mylist.erase(p);

So far I have only been able to do this by iterating through the list until I reach an item at the location p, and then using the erase method, which seems very inefficient.

like image 550
Bill Cheatham Avatar asked Sep 18 '12 14:09

Bill Cheatham


Video Answer


2 Answers

Nope, you'll have to use an iterator. I don't get why getting the pointer is easier than getting an iterator though...

like image 88
Luchian Grigore Avatar answered Sep 19 '22 23:09

Luchian Grigore


A std::list is not associative so there's no way you can use a pointer as a key to simply delete a specific element directly.

The fact that you find yourself in this situation points rather to questionable design since you're correct that the only way to remove the item from the collection as it stands is by iterating over it completely (i.e. linear complexity)

The following may be worth considering:

  1. If possible, you could change the list to a std::multiset (assuming there are duplicate items) which will make direct access more efficient.

  2. If the design allows, change the item that you're pointing to to incorporate a 'deleted' flag (or use a template to provide this) allowing you to avoid deleting the object from the collection but quickly mark it as deleted. Drawback is that all your software will have to change to accommodate this convention.

  3. If this is the only bit of linear searching and the collection is not big (<20 items say.) For the sake of expediency, just do the linear search as you've suggested but leave a big comment in the code indicating how you "completely get" how inefficient this is. You may find that this does not become a tangible issue in any case for a while, if ever.

I'm guessing that 3 is probably your best option. :)

like image 37
Component 10 Avatar answered Sep 19 '22 23:09

Component 10