ava*_*msi 2 c++ new-operator c++11
#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 << ' ';
}
}
Run Code Online (Sandbox Code Playgroud)
为什么这不起作用?我收到编译时错误说这个.
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'
Run Code Online (Sandbox Code Playgroud)
当我以注释方式初始化数组时,它工作正常.(显然)所以,我认为问题在于新的运营商.但我不明白它是什么.
new int[5]分配一个包含5个元素的数组,并返回指向第一个元素的指针.返回的类型是rvalue int*
int foo[5]是一个包含5个元素的数组.foo的类型是lvalue int [5]
循环范围要求它知道它迭代的对象的大小.它可以迭代数组,但不能迭代指针.考虑一下这段代码
int foo[4];
for (int a : (int *)foo) {}
Run Code Online (Sandbox Code Playgroud)
GCC 5.0也会产生错误"错误:'begin'未在此范围内声明"因为数组已衰减为指针.
| 归档时间: |
|
| 查看次数: |
969 次 |
| 最近记录: |