Keeping std::list iterators valid through insertion

前端 未结 4 1541
南笙
南笙 2020-12-20 21:16

Note: This is not a question whether I should \"use list or deque\". It\'s a question about the validity of iterators in the face of insert().


4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-20 21:51

    From http://www.sgi.com/tech/stl/List.html

    "Lists have the important property that insertion and splicing do not invalidate iterators to list elements, and that even removal invalidates only the iterators that point to the elements that are removed."

    Therefore, readpos should still be valid after the insert.

    However...

    std::list< char > is a very inefficient way to solve this problem. Each byte you store in a std::list requires a pointer to keep track of the byte, plus the size of the list node structure, two more pointers usually. That is at least 12 or 24 bytes (32 or 64-bit) of memory used to keep track of a single byte of data.

    std::deque< char> is probably a better container for this. Like std::vector it provides constant time insertions at the back however it also provides constant time removal at the front. Finally, like std::vector std::deque is a random-access container so you can use offsets/indexes instead of iterators. These three features make it an efficient choice.

提交回复
热议问题