2
#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++ for-每個循環在堆上分配數組
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'
當我以註釋的方式初始化數組時,它工作正常。 (明顯) 所以,我覺得問題是用新的運算符。但我不明白它是什麼。
因爲'arr'是一個'int *',而不是一個數組。在你註釋掉的代碼中,'arr'是一個數組,而不是指針。 [數組不是指針!](https://stackoverflow.com/q/4810664/241631) – Praetorian
對於動態分配的數組,情況當然有'std :: array'。 – PeterSW