C++的for语句

  • C++11引入了一种新的for循环形式,用于遍历某个特定的数组,区间,集合中的每个元素。
    以数组为例:
    for(int var : array)
    {
    //注意var的定义在括号内
    //doSomething
    }
  • 示例: ```cpp

    include

    using namespace std;

int main(int argc, char const *argv[]) { int arr[4] = {9, 5, 2, 7};

  1. cout << "传统way" << endl;
  2. for(int i = 0; i < 4; i++){
  3. cout << arr[i] << endl;
  4. }
  5. cout << "C++11 new way" << endl;
  6. for(int a : arr){
  7. cout << a << endl;
  8. }
  9. return 0;

} ```