Get index in C++11 foreach loop

后端 未结 5 919
太阳男子
太阳男子 2020-12-28 12:55

Is there a convenient way to get the index of the current container entry in a C++11 foreach loop, like enumerate in python:

for idx, obj in enu         


        
5条回答
  •  不知归路
    2020-12-28 13:54

    If you have access to Boost it's range adaptors can be used like this:

    using namespace boost::adaptors;
    
    for (auto const& elem : container | indexed(0))
    {
        std::cout << elem.index() << " - " << elem.value() << '\n';
    }
    

    Source (where there are also other examples)

提交回复
热议问题