如何最好地控制迭代方向? [英] How best to control iteration direction?

查看:159
本文介绍了如何最好地控制迭代方向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大型对象的容器,复制起来很贵。我有时必须正常地遍历整个容器,有时反过来。一旦我确定了迭代方向,我不需要改变飞行中,即不需要随机访问。

I have a container of large objects that are expensive to copy. I must sometimes iterate over the whole container normally, and sometimes in reverse. Once I determine the iteration direction, I don't need to change mid-flight, i.e. no random access needed.

我希望做这样的模式:

I'm hoping to do something like this pattern:

#include <iostream>
#include <vector>
using namespace std;
int main( int argc, char** )
{
    // pretend this is a vector of expensive objects
    vector<int> foo = {1,2,3,4,5};

    // calculate forward or backward iteration direction
    bool backwards = (argc > 1);

    if( backwards )
        // prepare backward iteration, but don't copy objects
    else
        // prepare forward iteration, but don't copy objects

    for( auto& i : /* either forward or backward */ )
    {
        // my loop body
        cout << i;
    }

    return 0;
}

这是一个C ++ 11程序,但我不认为真的帮我这里。我只是没有看到这样做的最好的方法。非常感谢您的帮助。

This is a C++11 program, but I don't think that really helps me here. I'm just not seeing the best way to do this. Thanks for any help.

推荐答案

C ++标准容器带有这些称为反向迭代器。使用 std :: vector :: rbegin() std :: vector :: rend()它通过向量反向迭代。 C ++ 03可以轻松做到:

The C++ standard containers come with these things called "reverse iterators". Use std::vector::rbegin() and std::vector::rend() to get an iterator that iterates backwards through the vector. C++03 can do this easily:

#include <iostream> 
#include <vector>  

// Use const reference to pass expensive-to-copy types
void loop_body(const int& i)
{
    std::cout << i;
}

int main( int argc, char** ) 
{ 
    // pretend this is a vector of expensive objects 
    std::vector<int> foo = {1,2,3,4,5}; 

    // calculate forward or backward iteration direction 
    bool backwards = (argc > 1); 

    if( backwards ) { 
        std::for_each(foo.rbegin(), foo.rend(), &loop_body);
    } else { 
        std::for_each(foo.begin(), foo.end(), &loop_body);
    } 
    return 0; 
} 

您可以使用C ++ 11中的lambdas:

You may be able to do this, using lambdas in C++11:

#include <iostream> 
#include <vector> 

int main( int argc, char** ) 
{ 
    // pretend this is a vector of expensive objects 
    std::vector<int> foo = {1,2,3,4,5}; 

    // calculate forward or backward iteration direction 
    bool backwards = (argc > 1); 

    // Use const reference to pass expensive-to-copy types
    auto loop_body = [](const int& i)
    {
        std::cout << i;
    };

    if( backwards ) { 
        std::for_each(foo.rbegin(), foo.rend(), loop_body);
    } else { 
        std::for_each(foo.begin(), foo.end(), loop_body);
    } 
    return 0; 
}

这篇关于如何最好地控制迭代方向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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