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
#include <iostream>
#include <string>
#include <map>
int main()
{
std::map<std::string, int> myMap{{"Rocky", 1}, {"Ronnie", 2}};
std::map<std::string, int>::const_iterator it;
for (it = myMap.begin(); it != myMap.end(); it++) {
// Test for first element
std::cout << (it == myMap.begin() ? "| " : "")
<< it->first << " = " << it->second
// Test for last element
<< (std::next(it) != myMap.end() ? ", " : " |");
}
std::cout << std::endl;
return 0;
}
// Output:
// | Rocky = 1, Ronnie = 2 |
References
comments powered by Disqus