C++用于在堆上分配数组的每个循环
C++ for-each loop with array allocated on the heap
#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'未在此范围内声明",因为数组已衰减为指针。
相关文章:
- C++中的高效循环缓冲区,它将被传递给C样式数组函数参数
- 使用for循环检查数组中的重复项
- 并行用于C++17中数组索引范围内的循环
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 程序在遍历所有值之前离开循环. 数组的
- 在C++中循环数组时访问结构属性
- 如何创建循环数组
- 查找 for 循环数组C++中存在最大值和最小值的值
- 有没有办法在 c++ 中创建循环数组
- OpenMP-每个线程的循环/数组界限
- 循环数组 - 从最后一个跳到第一个,反之亦然
- 循环数组时显示'stack smashing detected abc2 terminated Aborted'
- 使用循环数组实现矢量
- 为什么在循环数组时会得到奇怪的整数
- 循环数组-超出值
- 用于循环数组赋值的C++.正在返回垃圾邮件
- 在RapidJson中循环数组并获取对象元素
- 对于循环数组迭代,if循环测试索引是否为真/假,计算结果不正确
- c++循环/数组
- 有没有一种方法可以简化这个c++整数循环数组?