Unsigned int reverse iteration with for loops(使用 for 循环的无符号 int 反向迭代)
问题描述
我希望 for 循环中的迭代器变量将迭代反向为 0 作为 unsigned int
,我想不出与 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 反向迭代
基础教程推荐
- 初始化变量和赋值运算符 1970-01-01
- end() 能否成为 stl 容器的昂贵操作 2022-10-23
- 分别使用%o和%x以八进制或十六进制格式显示整 1970-01-01
- 明确指定任何或所有枚举数的整数值 1970-01-01
- 使用scanf()读取字符串 1970-01-01
- C++定义类对象 1970-01-01
- C++按值调用 1970-01-01
- C++输入/输出运算符重载 1970-01-01
- C++ #define 1970-01-01
- C语言访问数组元素 1970-01-01