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变量。

    完。

  • 相关阅读:
    ubuntu 安装chrome浏览器
    ubuntu下Xmodmap映射Esc和Ctrl_L
    ubuntu 设置主屏和副屏
    maven 第一次运行报错
    Intellij Idea 配置并发布tomcat项目
    Nginx跨域设置
    Inotify+rsync实现实时数据同步
    Ubuntu-18.04设置开机启动脚本
    CentOS开机自启动/etc/rc.local不执行的解决办法
    ELK之使用kafka作为消息队列收集日志
  • 原文地址:https://www.cnblogs.com/liyou-blog/p/4211654.html
Copyright © 2011-2022 走看看