How is end() implemented in STL containers?

后端 未结 6 2382
小蘑菇
小蘑菇 2021-02-19 12:32

So when we need to traverse a container from start to end we write something like

for (i = v->begin(); i != v->end(); i++)

assuming i

6条回答
  •  面向向阳花
    2021-02-19 12:54

    As some of the previous posters have stated end() is one past the end element. If you need to access the last element via iterators use iter = container.end() - 1; Otherwise, in the case of vectors, variable = someVector.back(); Assuming that variable is of the data type someVector contains.

    In regard to what guarantees that it points to the end, the container itself handles that internally. You just have to treat it like a blackbox like any other object and trust it does it correctly.

    Whenever the container is resized, it will track where the end is and will be up to date before you access end() again. Depending on the container however, if you have an iterator and alter it in some ways, it can invalidate the iterator and break your iteration process.

提交回复
热议问题