Need iterator when using ranged-based for loops

前端 未结 6 1967
失恋的感觉
失恋的感觉 2020-11-29 19:34

Currently, I can only do ranged based loops with this:

for (auto& value : values)

But sometimes I need an iterator to the value, instea

6条回答
  •  甜味超标
    2020-11-29 20:16

    Use the old for loop as:

    for (auto it = values.begin(); it != values.end();  ++it )
    {
           auto & value = *it;
           //...
    }
    

    With this, you've value as well as iterator it. Use whatever you want to use.


    EDIT:

    Although I wouldn't recommended this, but if you want to use range-based for loop (yeah, For whatever reason :D), then you can do this:

     auto it = std::begin(values); //std::begin is a free function in C++11
     for (auto& value : values)
     {
         //Use value or it - whatever you need!
         //...
         ++it; //at the end OR make sure you do this in each iteration
     }
    

    This approach avoids searching given value, since value and it are always in sync.

提交回复
热议问题