Admittedly, I'm just finding my footsteps in C++ but I don't understand the error here.
The following error gets displayed:
Error 1 error C3312: no callable 'begin' function found for type 'int []'
Error 2 error C3312: no callable 'end' function found for type 'int []'
Error 3 error C2065: 'i' : undeclared identifier
4 IntelliSense: this range-based 'for' statement requires a suitable "begin" function and none was found
Code:
#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 << " ";
}
}
Can't figure out what the problem is.
Range-based for loop in C++ Range-based for loop in C++ is added since C++ 11. It executes a for loop over a range. Used as a more readable equivalent to the traditional for loop operating over a range of values, such as all elements in a container.
To loop through a set of code a specified number of times, we can use the range() function, The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
Use the range-based for statement to construct loops that must execute through a range, which is defined as anything that you can iterate through—for example, std::vector , or any other C++ Standard Library sequence whose range is defined by a begin() and end() .
Range-based for loop in C++ Often the auto keyword is used to automatically identify the type of elements in range-expression. range-expression − any expression used to represent a sequence of elements.
Inside printArray
, a
is not an array! I know it looks like one, but it's not. int a[]
there means int* a
, due to a nasty legacy from the 1850s.
Here is the fix to your problem, passing in the array by reference and therefore keeping its full type (including numerical dimension):
#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);
}
(I've also removed some redundant code and that horrid system("pause")
: properly configure your execution environment rather than having your program take responsibility for blocking its caller when it's finished!)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With