Is there an equivalent to the range-based `enumerate` loop from python in modern C++?

后端 未结 9 1301
终归单人心
终归单人心 2020-12-21 00:48

Is there an equivalent to the range-based enumerate loop from python in C++? I would imagine something like this.

enumerateLoop (auto counter, a         


        
9条回答
  •  不知归路
    2020-12-21 01:33

    Boost::Range supports this as of 1.56.

    #include 
    #include 
    #include 
    #include 
    #include 
    
    
    int main(int argc, const char* argv[])
    {
        using namespace boost::assign;
        using namespace boost::adaptors;
    
        std::vector input;
        input += 10,20,30,40,50,60,70,80,90;
    
    //  for (const auto& element : index(input, 0)) // function version
        for (const auto& element : input | indexed(0))      
        {
            std::cout << "Element = " << element.value()
                      << " Index = " << element.index()
                      << std::endl;
        }
    
        return 0;
    }
    

提交回复
热议问题