I need to iterate over a vector from the end to the beginning. The "correct" way is
for(std::vector<SomeT>::reverse_iterator rit = v.rbegin(); rit != v.rend(); ++rit)
{
//do Something
}
When //do Something
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 != std::numeric_limits<unsigned>::max()
... or use UINT_MAX if you think its to verbose. – Cluefor (size_t i = v.size(); i --> 0; )
– Titrefor(unsigned i : boost::counting_range(v) | boost::adaptors::reversed)
– Temuco