gpt4 book ai didi

c++ - 基于范围的 for 循环会抛出带有数组参数的编译器错误

转载 作者:太空狗 更新时间:2023-10-29 23:50:36 30 4
gpt4 key购买 nike

不可否认,我只是在 C++ 中找到了我的脚步,但我不明白这里的错误。

显示以下错误:

错误 1 ​​error C3312:找不到类型“int []”的可调用“begin”函数

错误 2 error C3312: 找不到类型 'int []' 的可调用 'end' 函数

错误 3 error C2065: 'i' : undeclared identifier

4 IntelliSense:此基于范围的“for”语句需要合适的“开始”函数,但未找到

代码:

#include <iostream>

using namespace std;

void printArray(int[]);

int main() {
int a[] = { 1, 2, 3, 4, 5 };
printArray(a);
system("pause");
return 0;
}

void printArray(int a[]) {
for (int i : a) {
cout << i << " ";
}
}

无法弄清楚问题是什么。

最佳答案

printArray 中,a 不是数组!我知道它看起来像一个,但它不是。 int a[] 表示 int* a,因为 1850 年代留下了令人讨厌的遗产。

这是解决您的问题的方法,通过引用传递数组并因此保留其完整类型(包括数字维度):

#include <iostream>

template <size_t N>
void printArray(int (&a)[N]) {
for (int i : a) {
std::cout << i << " ";
}
}

int main() {
int a[] = { 1, 2, 3, 4, 5 };
printArray(a);
}

(我还删除了一些冗余代码和那个可怕的 system("pause"):正确配置您的执行环境,而不是让您的程序负责在调用程序时阻塞它的调用程序完成!)

( live demo )

关于c++ - 基于范围的 for 循环会抛出带有数组参数的编译器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28653967/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com