反向迭代向量
我需要从结尾到开头遍历一个向量.正确"的方式是
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
循环中看到该运算符时,我都必须重新阅读它以确保没有逐一错误. - 如果您更改条件中的间距,则可以使用 转到"运算符.
- Although
i
will wrap around toUINT_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 afor
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.
相关文章