在向量上反向迭代 [英] Iterating over a vector in reverse direction

查看:96
本文介绍了在向量上反向迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要遍历一个从末端到beginnig的向量。正确的方式是

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 - - 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 :)


  • 是无警告的


我希望我不是在寻找不存在的情况)

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

推荐答案

正如你所注意到的,条件 i> = 0 当它的无符号是条件总是true。当您初始化 i ,然后再次在每次迭代后,在检查循环条件后减去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 ,它不会依赖这种行为 - 它将工作相同if类型签名。

  • 它会调用 size()一次。

  • 它不使用> = 。每当我在中看到循环中的该运算符时,我必须重新读取它,以确保没有一个一个错误。

  • 如果更改条件中的间距,可以使用转到运算符

  • 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.

这篇关于在向量上反向迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆