Iterating over a vector in reverse direction

前端 未结 9 598
面向向阳花
面向向阳花 2020-12-08 04:36

I need to iterate over a vector from the end to the beginnig. The \"correct\" way is

for(std::vector::reverse_iterator rit = v.rbegin(); rit !=          


        
9条回答
  •  孤城傲影
    2020-12-08 05:07

    There's nothing to stop your reverse_iterator loop also using the index as described in multiple other answers. That way you can use the iterator or index as needed in the // do the work part, for minimal extra cost.

    size_t index = v.size() - 1;
    for(std::vector::reverse_iterator rit = v.rbegin(); 
        rit != v.rend(); ++rit, --index)
    {
      // do the work
    }
    

    Though I'm curious to know what you need the index for. Accessing v[index] is the same as accessing *rit.

提交回复
热议问题