Is it valid to use pointer-difference to find the index of an element within a range-based for loop?
A number of questions have been asked here concerning using indices and range-based loops together, but they almost all say to not use range-based loops if you also need the index of an element. But it seems like, at least for std::vector, std::array, and other containers which are contiguous in memory, you could use pointer differences to find the index of the element, provided you're iterating over element references. For example:
// Prints the indices of all elements for which Foo::bar is true.
void Example(const std::vector<Foo>& v) {
for (const auto& e : v) {
if (e.bar()) {
auto index = &e - v.data(); // Valid???
std::cout << index << std::endl;
}
}
}
The above code compiles and runs correctly, but I'm not completely certain of its validity. Can any language lawyers confirm or deny whether this is an acceptable method to find the index of the element?
In addition, is it safe to assume that if a container has a data() member, then its elements are contiguous in memory, and is therefore safe to use with this approach?