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 循环中的最后一次迭代?


基础教程推荐
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 设计字符串本地化的最佳方法 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01