c++ - 如何检测地图迭代器中的最后一个元素
问题描述
我希望能够在我的地图迭代器中检测到最后一次迭代。我将如何实现这一目标?
class JSON {
public:
static void stringify(map<string, string> data)
{
string base;
base += "{ ";
for (map<string, string>::iterator it = data.begin(); it != data.end(); ++it)
{
cout << it->first.c_str() << " => " << it->second.c_str() << endl;
}
}
};
解决方案
您可以像这样使用std::prev :
for(auto it = data.begin(); it != data.end(); ++it)
{
if(it == std::prev(data.end()))
{
// this is the last iteration
}
std::cout << it->first << " => " << it->second << '\n';
}
std::prev从其参数返回前一个迭代器。
推荐阅读
- node.js - macOS 升级后找不到 node/npm/nvm 错误
- html - 在 bootstrap4 中创建带有拆分按钮的下拉菜单
- highcharts - 是否可以创建具有条件着色并显示在图例中的图表?
- sql - ORA-00913“值太多”Oracle SQL
- sql - 多个表的 SQL 删除触发器
- logging - 根据结果值链接两个 Splunk Web 查询
- flutter - 如何检查 getLogin() 函数是否有效以显示登录是否成功
- python - 在深度复制期间防止参考重用
- maven - 无法在 Eclipse IDE 中使用 maven
- javascript - 将枚举映射到值