Range-based for-loop on array passed to non-main function
In C++, a range-based for-loop can be used to iterate over an array. However, when an array is passed to a non-main function, it decays into a pointer, losing its size information.
To resolve this issue and enable the use of a range-based for-loop, the array should be referenced instead of being passed as a pointer. This retains the array's size information. Here are the modified examples demonstrating the correct approach:
void foo(int (&bar)[3]);
int main() {
int bar[3] = {1,2,3};
for (int i : bar) {
cout << i << endl;
}
foo(bar);
}
void foo(int (&bar)[3]) {
for (int i : bar) {
cout << i << endl;
}
}
// Generic implementation
template <std::size_t array_size>
void foo(int (&bar)[array_size]) {
for (int i : bar) {
cout << i << endl;
}
}
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3