Spa*_*yan 1 c++ iterator c++11
I can't understand why the std::begin() function doesn't work when it is given an int * arr pointer, but it works with an int arr[] array.
This code doesn't work:
int *arr = new int[5]{ 1,2,3,4,5 };
if (find(begin(arr),end(arr),5)!=end(arr))
{
cout << "found";
}
Run Code Online (Sandbox Code Playgroud)
This code does work:
int arr2[5] = { 1,2,3,4,5 };
if (find(begin(arr2),end(arr2),5)!=end(arr2))
{
cout << "found";
}
Run Code Online (Sandbox Code Playgroud)
It doesn't work because int *arr isn't an array, it's a pointer. It happens to point to the first element of an array, but it's pointing to the element, not the array. Once it's converted to a pointer, the length information is lost.
迂腐注:这不是完全丢失,因为它实际上是隐藏在实现特定的方式使得分配器知道多少,当你以后释放delete[]它,但是这不暴露任何东西,但分配器,和它往往不等于实际由于分配器对齐要求,请求的大小不可用,因此此处没有用。
| 归档时间: |
|
| 查看次数: |
92 次 |
| 最近记录: |