C++基础学习:数组的遍历方法

#include <iostream>

int main(int argc, char** argv)
{
    int array[4] = {0,1,2,3};

    /**************遍历数组的方法一****************/
    size_t index = 0;
    while (index < std::size(array))
    {   
        std::cout << array[index] << std::endl;
        index++;
    }   


    /**************遍历数组的方法二****************/
    int* ptr_begin = std::begin(array);
    int* ptr_end = std::end(array);
    while (ptr_begin != ptr_end)
    {   
        std::cout << *ptr_begin << std::endl;
        ptr_begin++;
    }   

        
    /**************遍历数组的方法三****************/
    for (int x : array)
    {   
        std::cout << x << std::endl;
    }   


    return 0;
}

重点强调:

1、第一种方法中std::size()为元函数,在C++17中新增;

2、第二种方法采用首位指针进行实现,尾指针为数组的下一位;

3、第三种方法的实质是与第二种方法相同,优势是更为简单,可通过C++Insights进行对比学习,代码如下:

#include <iostream>

int main()
{
  int a[4] = {1, 2, 3, 4};
  {
    int (&__range1)[4] = a;
    for(int * __begin1 = __range1, *__end1 = __range1 + 4L; __begin1 != __end1; ++__begin1)                 
    {
      int x = *__begin1;
      std::cout.operator<<(x).operator<<(std::endl);
    }
    
  }
}


版权声明:本文为Dycadrwy原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。