zoukankan      html  css  js  c++  java
  • 基于范围的for循环

    语法:

     for ( for-range-declaration : expression )
    statement 

    注意一般用auto表达类型。不需要修改时常用引用类型

    例子:

     1 // range-based-for.cpp
     2 // compile by using: cl /EHsc /nologo /W4
     3 #include <iostream>
     4 #include <vector>
     5 using namespace std;
     6 
     7 int main() 
     8 {
     9     // Basic 10-element integer array.
    10     int x[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    11 
    12     // Range-based for loop to iterate through the array.
    13     for( int y : x ) { // Access by value using a copy declared as a specific type. 
    14                        // Not preferred.
    15         cout << y << " ";
    16     }
    17     cout << endl;
    18 
    19     // The auto keyword causes type inference to be used. Preferred.
    20 
    21     for( auto y : x ) { // Copy of 'x', almost always undesirable
    22         cout << y << " ";
    23     }
    24     cout << endl;
    25 
    26     for( auto &y : x ) { // Type inference by reference.
    27         // Observes and/or modifies in-place. Preferred when modify is needed.
    28         cout << y << " ";
    29     }
    30     cout << endl;
    31 
    32     for( const auto &y : x ) { // Type inference by reference.
    33         // Observes in-place. Preferred when no modify is needed.
    34         cout << y << " ";
    35     }
    36     cout << endl;
    37     cout << "end of integer array test" << endl;
    38     cout << endl;
    39 
    40     // Create a vector object that contains 10 elements.
    41     vector<double> v;
    42     for (int i = 0; i < 10; ++i) {
    43         v.push_back(i + 0.14159);
    44     }
    45 
    46     // Range-based for loop to iterate through the vector, observing in-place.
    47     for( const auto &j : v ) {
    48         cout << j << " ";
    49     }
    50     cout << endl;
    51     cout << "end of vector test" << endl;
    52 }
  • 相关阅读:
    Spring Boot源码分析-配置文件加载原理
    Spring Boot源码分析-启动过程
    Spring Cloud Alibaba基础教程:Nacos服务发现与配置管理
    JVM(九):垃圾回收算法
    JVM(八):Java 对象模型
    JVM(七):JVM内存结构
    JVM(六):探究类加载过程-下
    JVM(五):探究类加载过程-上
    JVM(四):深入分析Java字节码-下
    JVM(三):深入分析Java字节码-上
  • 原文地址:https://www.cnblogs.com/raichen/p/5696884.html
Copyright © 2011-2022 走看看