Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
267 views
in Technique[技术] by (71.8m points)

c++ - Iterating over a vector in reverse direction

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

for(std::vector<SomeT>::reverse_iterator rit = v.rbegin(); rit != v.rend(); ++rit)
{
    //do Something
}

When doSomething involves knowing the actual index, then some calculations need to be done with rit to obtain it, like index = v.size() - 1 - (rit - v.rbegin)

If the index is needed anyway, then I strongly believe it is better to iterate using that index

for(int i = v.size() - 1; i >= 0; --i)
{
    //do something with v[i] and i; 
}

This gives a warning that i is signed and v.size() is unsigned. Changing to

for(unsigned i = v.size() - 1; i >= 0; --i) is just functionally wrong, because this is essentially an endless loop :)

What is an aesthetically good way to do what I want to do which

  • is warning-free
  • doesn't involve casts
  • is not overly verbose

I hope I am not looking for something that doesn't exist :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...