我需要从结尾到开头遍历一个向量.正确"的方式是
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
}
当doSomething涉及知道实际的索引时,那么需要用rit做一些计算才能得到它,比如index = v.size() - 1 - (rit - v.rbegin)
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;
}
这会警告 i
已签名且 v.size()
未签名.更改为
This gives a warning that i
is signed and v.size()
is unsigned.
Changing to
for(unsigned i = v.size() - 1; i >= 0; --i)
只是功能错误,因为这本质上是一个无限循环 :)
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
我希望我不是在寻找不存在的东西:)
I hope I am not looking for something that doesn't exist :)
如您所见,i >= 0
条件在未签名时的问题在于条件总是真的.不是在初始化 i
时减 1,然后在每次迭代后再次减 1,而是在检查循环条件后减 1:
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:
i
会在循环结束时返回到 UINT_MAX
,但它并不依赖这种行为——它会起作用如果类型已签名,则相同.依赖未签名的环绕对我来说有点像黑客.size()
.>=
.每当我在 for
循环中看到该运算符时,我都必须重新阅读它以确保没有逐一错误.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.size()
exactly once.>=
. 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.这篇关于反向迭代向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!