简体   繁体   English

使用指针擦除std :: list中的元素?

[英]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). 您可以对列表中的元素进行[线性]搜索,将每个元素的地址与指针进行比较( std::find_if将符合条件)。 Of course, you will still be using an iterator in the end, because that's what list::erase needs. 当然,最后你仍然会使用迭代器,因为这就是list::erase需要的东西。

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. 列表节点包含的数据多于仅包含的对象(例如指向前一个节点和下一个节点的指针),但您的原始指针仅指向包含的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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