如何检测 std::map 循环中的最后一次迭代?

2022-01-10 00:00:00 iterator c++ maps stl

我正在尝试找出最好的方法来确定我是否处于地图上循环的最后一次迭代中,以便执行以下操作:

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 (iter = someMap.begin(); iter != someMap.end(); ++iter) {
    bool last_iteration;
    // do something for all iterations
    if (!last_iteration) {
        // do something for all but the last iteration
    }
}

似乎有几种方法可以做到这一点:随机访问迭代器、distance 函数等.规范的方法是什么?

There seem to be several ways of doing this: random access iterators, the distance function, etc. What's the canonical method?

地图没有随机访问迭代器!

no random access iterators for maps!

推荐答案

规范?我不能这么说,但我建议

Canonical? I can't claim that, but I'd suggest

final_iter = someMap.end();
--final_iter;
if (iter != final_iter) ...

已编辑以按照 KTC.(谢谢!有时你走得太快,把最简单的事情搞砸了……)

Edited to correct as suggested by KTC. (Thanks! Sometimes you go too quick and mess up on the simplest things...)

相关文章