zoukankan      html  css  js  c++  java
  • 数组下标索引的循环原来可以这样写

    一般我会这样写:

     1 #include "stdafx.h"
     2 #include <Windows.h>
     3 
     4 int _tmain(int argc, _TCHAR* argv[])
     5 {
     6     int arr[]={100,101,102,103,104,105,106,107,108,109};
     7     int count=sizeof(arr)/sizeof(int);
     8     int index=0;
     9 
    10     ///////////////////////////here/////////////////////////////////////////
    11     for (; index<count; index++)
    12     {
    13         printf("arr[%d]=%d
    ", index, arr[index]);
    14         Sleep(900);
    15         if(index+1==count)
    16             index=-1;
    17     }
    18     //////////////////////////////////////////////////////////////////////////
    19 
    20     getchar();
    21     return 0;
    22 }

    今天看了live555的函数:void BasicTaskScheduler::SingleStep(unsigned maxDelayTime),发现了新的非常简洁的写法:

     1 #include "stdafx.h"
     2 #include <Windows.h>
     3 
     4 int _tmain(int argc, _TCHAR* argv[])
     5 {
     6     int arr[]={100,101,102,103,104,105,106,107,108,109};
     7     int count=sizeof(arr)/sizeof(int);
     8     int index=0;
     9 
    10     ///////////////////////////////here/////////////////////////////////////
    11     do 
    12     {
    13         printf("arr[%d]=%d
    ", index, arr[index]);
    14         index=(index+1) % count;
    15         Sleep(900);
    16     } while (true);
    17     //////////////////////////////////////////////////////////////////////////
    18 
    19     getchar();
    20     return 0;
    21 }

    对比可知,第一个种写法,要在两个地方控制index变量(第11行,第15到第16行);而第二种写法,只需要在一个地方用一行代码(第14行),就能控制index变量。

    完。

  • 相关阅读:
    Codeforces Round #136 (Div. 1) B. Little Elephant and Array
    洛谷 P2966 [USACO09DEC]牛收费路径Cow Toll Paths
    cogs 969. [NOIP2006] 数列
    防止xss(跨站脚本攻击)
    ☀【插件】iScroll
    ☀【移动优化】
    ☀【Zepto】
    ☀【JS】Code
    ☀【响应式设计】屏幕尺寸
    CODEVS——T2744 养鱼喂妹纸
  • 原文地址:https://www.cnblogs.com/liyou-blog/p/4211654.html
Copyright © 2011-2022 走看看