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

后端 未结 5 548
猫巷女王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 11:02

    Adding, removing and moving the elements within the list or across several lists does not invalidate the iterators or references. An iterator is invalidated only when the corresponding element is deleted.

    Source: https://en.cppreference.com/w/cpp/container/list

    So a std::list<>::iterator is only invalidated when the corresponding element is deleted. So yes, as long as you make sure that the corresponding element exists (which you will anyway have to do in your scenario of storing/passing around a pointer to anything) you can save and/or pass around the iterator throughout the lifetime of your program.

    Now, an iterator is nothing but a pointer in disguise. So, if you prefer to save/pass around the corresponding pointer instead of iterator, you can always first convert the iterator to the pointer as @Aaron McDaid suggested.

    int * ptr = &*it; // get a pointer to the same element.

提交回复
热议问题