简体   繁体   中英

Erase element from std::list using a pointer?

class SororityBeerExpo{
public:

     std::list<LaysCrankdPepChip> m_chipList;

     void destroyChip(LaysCrankdPepChip * target)
     {
         // m_chipList needs to erase that which is pointed at by target but
         // erase() requires an iterator which is not what we got to work with
         // remove() needs a value which is not right either
     }
}

My question, is how would one delete an element in a list, with a pointer that points to that element? I would like to do this without using Iterators in place of pointers.

You can do a [linear] search for the element in the list, comparing the address of each element to your pointer ( std::find_if will fit the bill). Of course, you will still be using an iterator in the end, because that's what list::erase needs.

You can't do it directly (although see Benjamin's answer for an indirect way of doing it). A list node contains more data than just the object being contained (eg pointers to the previous and next nodes), but your raw pointer only points to the contained object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM