First & Last Element in C++ Iterator Loop
C++
Iterator-based iteration in C++ works for all containers, including lists and associative containers.
When looping with an iterator, the index of the current iteration isn’t immediately obvious, unless you resort to incrementing a counter.
First Element
It’s pretty straightforward to get the first element - you just compare the iterator at the current iteration through container
with container.begin()
Last Element
To get the last element in an iterator loop you can use std::next()
(from C++11). The loop is generally terminated by iterator != container.end()
, where end()
returns an iterator that points to the past-the-end element. If container.next(iterator) == container.end()
returns true, you’re on the last element.
Example
References
comments powered by Disqus