【发布时间】:2022-01-09 01:24:21
【问题描述】:
我知道如何从指针中获取指针并添加索引。但是如果你只有一个指向数组开头的指针和一个指向一个元素元素的指针,是否可以获得数组的索引?
#include <iostream>
#include <array>
auto pointer_from_diff(auto *x, auto *y) -> auto {
return // ? what here?
}
auto main() -> int {
auto x = std::array{1, 2, 3, 4};
auto *p = &x[2];
std::cout << pointer_from_diff(x.data(), p) << std::endl;
}
因为似乎有人不喜欢用 c 标记的问题,所以这里有一些实际的 c 代码,供那些不会说 c++ 的人使用。
#include <stdio.h>
int pointer_from_diff(int *x, int *y) {
return ?;// ? what here?
}
int main() {
int x[] = {1, 2, 3, 4};
int *p = &x[2];
int index = pointer_from_diff(x, p);
printf("%d", pointer_from_diff(x, p));
}
注意:我将其标记为 c++/c,不是因为我想使用 c,而是因为我猜测这两种语言的解决方案是相似的。因此,可以在 c++ 中实现的 c 解决方案是可以接受的。
对于 c++ 版本中的大声笑,我也过度/误用 auto,这与问题无关。
【问题讨论】:
-
你只是减去。
-
std::distance是你的朋友 :-) -
pointer + number==pointer所以即使从逻辑上你也可以推断出pointer - pointer==number。 -
对于大声笑:加法的逆是减法。直觉并不总是有帮助,但有时