Unsigned int reverse iteration with for loops(带 for 循环的无符号 int 反向迭代)
问题描述
我希望 for 循环中的迭代器变量作为 unsigned int 反向迭代到 0,我想不出与 i > 类似的比较.-1,就像如果它是 signed int 一样.
I want the iterator variable in a for loop to reverse iterate to 0 as an unsigned int, and I cannot think of a similar comparison to i > -1, as you would do if it was a signed int.
for (unsigned int i = 10; i <= 10; --i) { ... }
但这似乎很不清楚,因为它依赖于无符号整数的数值溢出超过 10.
But this seems very unclear, as it is relying on the numerical overflow of the unsigned integer to be above 10.
也许我只是没有清醒的头脑,但有什么更好的方法可以做到这一点...
Maybe I just don't have a clear head, but whats a better way to do this...
免责声明:这只是一个简单的用例,10 的上限是微不足道的,它可以是任何东西,并且 i 必须是一个 unsigned int代码>.
Disclaimer: this is just a simple use case, the upper limit of 10 is trivial, it could be anything, and i must be an unsigned int.
推荐答案
可以使用
for( unsigned int j = n; j-- > 0; ) { /*...*/ }
它从 n-1 向下迭代到 0.
It iterates from n-1 down to 0.
这篇关于带 for 循环的无符号 int 反向迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:带 for 循环的无符号 int 反向迭代
基础教程推荐
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- CString 到 char* 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 初始化列表*参数*评估顺序 2021-01-01
