C++用于在堆上分配数组的每个循环

C++ for-each loop with array allocated on the heap

本文关键字:循环 数组 分配 用于 C++      更新时间:2023-10-16
#include <bits/stdc++.h>
using namespace std;
int main(){
    ios::sync_with_stdio(0); cin.tie(0);
    auto arr = new int[5];
    // int arr[5] = {1, 2, 3, 4, 5};
    for (auto i: arr){
        cout << i << ' ';
    }
}

为什么不起作用?我收到一个编译时错误,上面写着这句话。

C.cpp: In function 'int main()':
C.cpp:8:15: error: 'begin' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
     begin(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1206:5: note:   'std::begin'
C.cpp:8:15: error: 'end' was not declared in this scope
  for (auto i: arr){
               ^
C.cpp:8:15: note: suggested alternatives:
In file included from /usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/x86_64-pc-cygwin/bits/stdc++.h:94:0,
                 from C.cpp:1:
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'
     end(const valarray<_Tp>& __va)
     ^
/usr/lib/gcc/x86_64-pc-cygwin/4.9.2/include/c++/valarray:1226:5: note:   'std::end'

当我以注释的方式初始化数组时,它工作得很好。(显然(所以,我认为问题出在新的运营商身上。但我不明白它是什么。

new int[5]分配一个由5个元素组成的数组,并返回一个指向第一个元素的指针。返回类型为rvalue int*

CCD_ 3是一个由5个元素组成的数组。foo的类型为lvalue int [5]

循环的范围要求它知道正在迭代的对象的大小。它可以对数组进行迭代,但不能对指针进行迭代。考虑一下这个代码,

int foo[4];
for (int a : (int *)foo) {}

GCC 5.0还产生一个错误"error:'begin'未在此范围内声明",因为数组已衰减为指针。