Get pointer to node in std::list or std::forward_list

后端 未结 5 616
猫巷女王i
猫巷女王i 2021-01-14 10:41

I am planning to use std::list in my code, I decided not to use std::forward_list, because for deletions (I figured) the whole list will have to traversed, O(N) complexity f

5条回答
  •  萌比男神i
    2021-01-14 10:53

    For lists, an iterator is valid even if other items in the list are erased. It becomes garbage when that item the iterator references in the list is removed.

    So, as long as you know the iterator you're passing around isn't being removed by some other piece of code, they're safe to hold onto. This seems fragile though.

    Even if there was a construct outside of iterators to reference a node in the list, it would suffer from the same fragility.

    However, you can have each node contain an std::shared_ptr to the data it stores instead of the object itself and then pass around std::weak_ptr's to those objects and check for expired before accessing those weak_ptr's.

    eg

    instead of

    std::list foo;
    

    you would have

    std::list> foo;
    

    have a look here for info on weak_ptr's

提交回复
热议问题