c++ - 双向迭代容器
问题描述
有没有比下面的代码更好的方法,使用相同的迭代器在任一方向上迭代容器?
#include <iostream>
#include <map>
int main()
{
const bool descend = false;
std::map<int, int> mapp;
mapp[1] = 1;
mapp[2] = 2;
mapp[3] = 3;
mapp[4] = 4;
std::map<int, int>::iterator startIter = descend ? --(mapp.end()) : mapp.begin();
std::map<int, int>::iterator endIter = descend ? --(mapp.begin()) : mapp.end();
while (startIter != endIter)
{
std::cout << startIter->first << std::endl;
descend ? --startIter : ++startIter;
}
}
解决方案
您的代码无效,因为此语句--(mapp.begin())
导致 UB。我会写一个薄包装:
template<class Iter, class F>
void apply( Iter begin, Iter end, F f, bool forward )
{
while( begin != end )
f( forward ? *begin++ : *--end );
}
或者只是简单地将循环重写为:
auto begin = mapp.begin();
auto end = mapp.end();
while ( begin != end)
{
const auto &p = forward ? *begin++ : *--end;
std::cout << p.first << std::endl;
}
推荐阅读
- python - Python中的Java SortHashMap等价物
- java - OneToMany 关系更新/替换子功能
- html - 使弹性项目在悬停时增长而不影响其他弹性元素
- javascript - 为什么功能性反应组件被破坏并再次安装?
- python - 将 .txt 文件中的 HTML 代码隐藏为纯文本
- javascript - 无论 Material-UI Accordion 中不同内容的大小如何对齐按钮?
- google-apps-script - 如何将邮件从我的 ID 转移到共享表单的人的 ID?
- swiftui - 在 swiftUI 中使用 onContinueUserActivity 处理启动并发症时的 ActivityType 是什么
- c# - ASP.NET 网络性能
- css - 如何在 chrome 中消除此输入角上的轻微白色边框(包括代码沙箱)?