I tried to iterate through the following arr array . but Visual studio shows it has a error.
void printArray(int* arr)
{
for (int i : arr)
{
cout << i << ",";
}
}
I tried to iterate through the following arr array . but Visual studio shows it has a error.
void printArray(int* arr)
{
for (int i : arr)
{
cout << i << ",";
}
}
In your example arr
is not an array, it is a pointer. Therefore, it is impossible to determine the number of items in your array from the pointer alone: this is the reason why APIs that take a pointer to array's initial element also take the number of elements in that array, for example:
void printArray(int *arr, size_t count)
Since the number of items in the array is unknown, arr
cannot be used in a range loop.
You copy range data into std::vector
to use it in a range loop:
void printArray(int *arr, size_t count) {
for (int i : vector<int>(arr, arr+count)) {
cout << i << ",";
}
}
However, passing std::vector
in place of a pointer is a much better way of achieving the same effect with idiomatic C++ code.