c++ - 如何最好地控制迭代方向?

标签 c++ c++11 iteration

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

我希望做这样的模式:

#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 程序,但我不认为这对我有什么帮助。我只是没有看到最好的方法来做到这一点。感谢您的帮助。

最佳答案

C++ 标准容器带有这些称为“反向迭代器”的东西。使用 std::vector::rbegin()std::vector::rend() 获得一个迭代器,它通过 vector 向后迭代。 C++03 可以轻松做到这一点:

#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 中的 lambda 执行此操作:

#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; 
}

关于c++ - 如何最好地控制迭代方向?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9022692/

相关文章:

python - 将值添加到列表中直到 Python 中的某个索引

arrays - 如何将命名列表转换为对象数组

c++ - 从函数返回指针

c++ - CreateWindowEx 返回 NULL

c++ - 在命令行 OSX 应用程序中创建警报/消息框

C++重用对象以使用抽象基类实现多态性

c++ - 禁用 MSVC 警告 C4482 是否安全?

c++ - 混合 C++11 std::thread 和 C 系统线程(即 pthreads)

c++ - C++11 中的类型转发

python - 如何在python中向后循环?