为什么基于范围的for循环不适用于数组的指针?
auto pCollection = new int[3] { 0,1,2 };
// error C3312: no callable 'begin' function found for type 'int *'
for (auto value : pCollection)
{
std::cout << value << std::endl;
}
delete[] pCollection;
Run Code Online (Sandbox Code Playgroud)
但可以在数组上使用:
int collection[3]{ 0,1,2 };
for (auto value : collection)
{
std::cout << value << std::endl;
}
Run Code Online (Sandbox Code Playgroud)
指针不是数组.从指针本身无法知道指针指向的位置可能有多少元素,也可能没有多少元素.