Iterating over a vector in reverse direction

前端 未结 9 572
面向向阳花
面向向阳花 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条回答
  •  -上瘾入骨i
    2020-12-08 04:59

    I would prefer the reverse iterator variant, because it's still easy to interpret and allows to avoid index-related errors.

    Sometimes you can simply use the BOOST_REVERSE_FOREACH, which would make your code look the following way:

    reverse_foreach (int value, vector) {
       do_something_with_the_value;
    }
    

    Actually speaking, you can always use foreach statements for these kinds of loops, but then they become a bit unobvious:

    size_t i = 0;
    
    foreach (int value, vector) {
       do_something;
       ++i;
    }
    

提交回复
热议问题