以双向方式迭代容器 [英] Iterating over a container bidirectionally

查看:147
本文介绍了以双向方式迭代容器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有比下面的代码更好的方法,使用相同的迭代器在任一方向迭代容器?

Is there a better way than the below code, to iterate over a container in either direction, using the same iterators?

#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。我会写一个薄的包装器:

Your code is invalid as this statement --(mapp.begin()) leads to UB. I would write a thin wrapper:

template<class Iter, class F>
void apply( Iter begin, Iter end, F f, bool forward )
{
    while( begin != end ) 
        f( forward ? *begin++ : *--end );
}

实例

或只是简单地将你的循环重写为:

or just simply rewrite your loop into:

auto begin = mapp.begin();
auto end = mapp.end();
while ( begin != end)
{
    const auto &p = forward ? *begin++ : *--end;
    std::cout << p.first << std::endl;
}

这篇关于以双向方式迭代容器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆