How can I detect the last iteration in a loop over std::map?(如何检测 std::map 循环中的最后一次迭代?)
问题描述
我正在尝试找出最好的方法来确定我是否处于地图上循环的最后一次迭代中,以便执行以下操作:
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...)
这篇关于如何检测 std::map 循环中的最后一次迭代?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何检测 std::map 循环中的最后一次迭代?
基础教程推荐
- 这个宏可以转换成函数吗? 2022-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
