在for循环中计数 [英] Counting down in for-loops

查看:212
本文介绍了在for循环中计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信(从一些研究阅读),在for循环倒计时实际上是更有效和更快的运行时间。我的完整的软件代码是C ++



我现在有这个:

  for(i = 0; i< domain; ++ i){

my'i'is unsigned resgister int,
也是'domain'是unsigned int



用于遍历数组,例如

  array [i] = do stuff 


$ b $我可以想象这个答案是相当微不足道的,但是我不能得到这个答案。我的头圆。



更新:'做东西'不依赖于以前或以后的迭代。 for循环中的计算与i的迭代无关。 (我希望这是有道理的)。

更新:为了实现运行时加速与我的for循环,我倒计数,如果是这样删除未签名的部分,当我delcaring int,或者其他什么方法?



请帮忙解决方案

我猜你向后的循环看起来像这样:

  for(i = domain  -  1; i> = 0; --i){

在这种情况下,因为 i 无符号,它总是 大于或等于零。当你递减一个等于零的无符号变量时,它将绕回一个非常大的数字。解决办法是让 i 签名,或者像这样改变for循环中的条件:

  for(i = domain-1; i> = 0&& i< domain; --i){
域到 1 ,而不是从 domain - 1 to 0

 <$ (i = domain; i> = 1;  -  i){
array [i-1] = ...; //注意你必须从循环里面减去1

$ $ $

I believe (from some research reading) that counting down in for-loops is actually more efficient and faster in runtime. My full software code is C++

I currently have this:

for (i=0; i<domain; ++i) {

my 'i' is unsigned resgister int, also 'domain' is unsigned int

in the for-loop i is used for going through an array, e.g.

array[i] = do stuff

converting this to count down messes up the expected/correct output of my routine.

I can imagine the answer being quite trivial, but I can't get my head round it.

UPDATE: 'do stuff' does not depend on previous or later iteration. The calculations within the for-loop are independant for that iteration of i. (I hope that makes sense).

UPDATE: To achieve a runtime speedup with my for-loop, do I count down and if so remove the unsigned part when delcaring my int, or what other method?

Please help.

解决方案

I'm guessing your backward for loop looks like this:

for (i = domain - 1; i >= 0; --i) {

In that case, because i is unsigned, it will always be greater than or equal to zero. When you decrement an unsigned variable that is equal to zero, it will wrap around to a very large number. The solution is either to make i signed, or change the condition in the for loop like this:

for (i = domain - 1; i >= 0 && i < domain; --i) {

Or count from domain to 1 rather than from domain - 1 to 0:

for (i = domain; i >= 1; --i) {
    array[i - 1] = ...; // notice you have to subtract 1 from i inside the loop now
}

这篇关于在for循环中计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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