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
}
当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
iwill wrap around toUINT_MAXat 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 aforloop, 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.
这篇关于反向迭代向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:反向迭代向量
基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
