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 循环中的最后一次迭代?
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- CString 到 char* 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
