Caching the end iterator - Good idea or Bad Idea?

前端 未结 8 1884
臣服心动
臣服心动 2021-02-04 03:36

Generally speaking is it a good idea to cache an end iterator (specifically STL containers) for efficiency and speed purposes? such as in the following bit of code:



        
8条回答
  •  眼角桃花
    2021-02-04 04:11

    The invalidation rules (for iterators) is defined very explicitly for each type of container. I find the SGI site very useful http://www.sgi.com/tech/stl/table_of_contents.html

    Specifically for vectors I find:

    [5] A vector's iterators are invalidated when its memory is reallocated. Additionally, inserting or deleting an element in the middle of a vector invalidates all iterators that point to elements following the insertion or deletion point. It follows that you can prevent a vector's iterators from being invalidated if you use reserve() to preallocate as much memory as the vector will ever use, and if all insertions and deletions are at the vector's end.

提交回复
热议问题