I\'m trying to figure out the best way to determine whether I\'m in the last iteration of a loop over a map in order to do something like the following:
for
The following code would be optimized by a compiler so that to be the best solution for this task by performance as well as by OOP rules:
if (&*it == &*someMap.rbegin()) {
//the last iteration
}
This is the best code by OOP rules because std::map has got a special member function rbegin for the code like:
final_iter = someMap.end();
--final_iter;
Since C++11, you can also use std::next()
for (auto iter = someMap.begin(); iter != someMap.end(); ++iter) {
// do something for all iterations
if (std::next(iter) != someMap.end()) {
// do something for all but the last iteration
}
}
Although the question was asked a while ago, I thought it would be worth sharing.
Surprised no one mentioned it yet, but of course boost has something ;)
Boost.Next (and the equivalent Boost.Prior)
Your example would look like:
for (iter = someMap.begin(); iter != someMap.end(); ++iter) {
// do something for all iterations
if (boost::next(iter) != someMap.end()) {
// do something for all but the last iteration
}
}
Canonical? I can't claim that, but I'd suggest
final_iter = someMap.end();
--final_iter;
if (iter != final_iter) ...
Edited to correct as suggested by KTC. (Thanks! Sometimes you go too quick and mess up on the simplest things...)
Here's my optimized take:
iter = someMap.begin();
do {
// Note that curr = iter++ may involve up to three copy operations
curr = iter;
// Do stuff with curr
if (++iter == someMap.end()) {
// Oh, this was the last iteration
break;
}
// Do more stuff with curr
} while (true);
This seems like the simplest:
bool last_iteration = iter == (--someMap.end());