Keeping separate pointers to container items

This question already has an answer here:

  • Iterator invalidation rules 4 answers

  • For a std::vector , you can use the reserve member function to ensure that a contiguous block of memory is preallocated for the maximum number of elements you require. This means that the elements are not copied around unless you exceed the reserved capacity.

    All pointers to elements in a std::deque are also invalidated when inserting or erasing elements. However, a std::list is guaranteed not to invalidate any pointers in these situations other than the pointer to the element you are erasing.


    Lists are sequence containers that allow you to insert and erase anywhere and iterate in both directions. The main drawback of lists compared to the vectors is that they lack direct access to the elements by their position.

    Deques are sequence containers as well. They come with dynamic sizes that can be expanded or contracted on both ends. They are quite similar to vector and provide you direct access to the elements by their position.

    You need to ask yourself: what kind of operations do I need to do on the container ?

    Note that list and forward_list preserves validity of the container when manipulated, whereas deque invalidates it.

    Visit http://www.cplusplus.com/ for more information about containers in c++.


    The solution is to have the vector hold pointers to the objects rather than having it directly contain the objects. Then you don't have to be concerned about the vector resizing because when it resizes, the objects will remain at their original location in memory.

    链接地址: http://www.djcxy.com/p/73340.html

    上一篇: 操作之后,迭代器会失效吗?

    下一篇: 保留单独的指向容器项目的指针