How can I detect the last iteration in a loop over std::map?
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...)
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.
This seems like the simplest:
bool last_iteration = iter == (--someMap.end());