我不明白在此代码中find函数如何能够返回元素在数组中首次出现的位置。下面的代码将打印4。
据我了解,arr应该具有数组的基地址,而ptr应该具有第一次出现时它们的首次出现的内存位置的地址55,这两个都是:Ox470000和Ox470010,所以我的问题是为什么我们得到4当我们打印时(ptr-arr)。
#include <iostream>
#include <algorithm>
using namespace std; //for find()
int arr[] = { 11, 22, 33, 44, 55, 66, 77, 88 };
int main()
{
int* ptr;
ptr = find(arr, arr+8, 55); //find first 55
cout << "First object with value 33 found at offset"
<< (ptr-arr) << endl;
cin>>arr[0];
return 0;
}
最佳答案
这是cppreference的报价:
换句话说,您的减法不是将偏移量作为字节(0x10
)返回,而是作为索引位置的差异(4-0
)返回。
关于c++ - 不确定查找功能在CPP中的工作方式,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/27469408/