Iterating over a vector in reverse direction

前端 未结 9 548
面向向阳花
面向向阳花 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 04:56

    Hi i think better way use iterator as you use in first sample and if you need get iterator index you can use std::distance to calculate it, if i understand your question

    0 讨论(0)
  • 2020-12-08 04:57

    Try out a do while :

    std::vector<Type> v;
    // Some code 
    if(v.size() > 0)
    {
        unsigned int i = v.size() - 1;
        do
        {
            // Your stuff
        }
        while(i-- > 0);
    }
    
    0 讨论(0)
  • 2020-12-08 04:57
    for (it = v.end()-1; it != v.begin()-1; --it)
    {
    }
    

    The "goes to" operator definitely messes with my head.

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2020-12-08 05:02

    As you've noted, the problem with a condition of i >= 0 when it's unsigned is that the condition is always true. Instead of subtracting 1 when you initialize i and then again after each iteration, subtract 1 after checking the loop condition:

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

    I like this style for several reasons:

    • Although i will wrap around to UINT_MAX at the end of the loop, it doesn't rely on that behavior — it would work the same if the types were signed. Relying on unsigned wraparound feels like a bit of a hack to me.
    • It calls size() exactly once.
    • It doesn't use >=. Whenever I see that operator in a for loop, I have to re-read it to make sure there isn't an off-by-one error.
    • If you change the spacing in the conditional, you can make it use the "goes to" operator.
    0 讨论(0)
  • 2020-12-08 05:05

    loop condition i != std::numeric_limits<unsigned>::max() ... or use UINT_MAX if you think its to verbose. or another way:
    for(unsigned j=0, end=v.size(), i=end-1; j<end; --i, ++j)
    or
    for(unsigned end=v.size(), i=end-1; (end-i)<end; --i)

    0 讨论(0)
提交回复
热议问题