c++: Is it valid to subtract an iterator from an element pointer to get a valid index?

  abseil, c++, iterator

I came across the following code:

for (int i = 0; i < subspan.size(); i++) {
  ...
  int size = size_table[&(subspan[i]) - fullspan.begin()];
  ...
}

subspanand fullspan are both of type std::span (actually absl::Span from Google’s Abseil library, but they seem to be pretty much the same as std::span) and are views into the same data array (with fullspan spanning the entire array).

Is this valid and well defined code? It seems to depend on the iterator being converted to the corresponding pointer value when the - operator is applied together with a lhs pointer.

Source: Windows Questions C++

LEAVE A COMMENT