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 }
  • 相关阅读:
    博客搬到CSDN了,以后就老实的呆在这儿吧~~
    Android对px和dip进行尺寸转换的方法
    获取Java的32位MD5实现
    GDI+ Hello World
    WTL对话框添加背景图片
    WTL对话框添加背景图片
    WTL设置对话框背影色
    WTL设置对话框背影色
    使用CStatic显示图片(bmp、ico、png)
    WTL Picture Control显示图片
  • 原文地址:https://www.cnblogs.com/raichen/p/5696884.html
Copyright © 2011-2022 走看看