Iterating over a vector in reverse direction

前端 未结 9 549
面向向阳花
面向向阳花 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<SomeT>::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.

    0 讨论(0)
  • 2020-12-08 05:10

    I think that:

    for(unsigned i = v.size() - 1; i >= 0; --i)
    

    is fine if you check

    !v.empty()
    

    earlier.

    0 讨论(0)
  • 2020-12-08 05:14

    to be aesthetically pleasing! ;)

    for(unsigned i = v.size() - 1; v.size() > i; --i)
    
    0 讨论(0)
提交回复
热议问题