c++c++20stdvectorstd-span

Is it possible to recover the actual index of elements in a `std::span`?


I have a class with a std::vector member variable. I also have a member function that takes a contiguous range in that std::vector, specified by two size_t parameters, and performs some operations on it.

class MyClass {
    std::vector<int> objects;

public:

    void func(size_t start_index, size_t end_index); 
}

Now, I want to replace the two size_t parameters with a single std::span parameter to improve safety, readability, and maintainability. There's one obstacle, however: in my function, I need to be able to recover the first index of the range in the original std::vector. As in, I need to be able to find where the std::span begins in the original array. Is there a way to do this? If not, then do I have no choice but to use my original clunky design?

(I initially tried recovering the first index by subtracting objects.begin() from the begin() iterator of the std::span parameter I had, but this resulted in a compilation error.)


Solution

  • If you have the original vector available, then the index in the vector of the first element in the span is

    auto index = (span.data() - vector.data());
    

    (I initially tried recovering the first index by subtracting objects.begin() from the begin() iterator of the std::span parameter I had, but this resulted in a compilation error.)

    That's not going to work. You cannot subtract or get the difference between two iterators from different containers. Their data on the other hand is pointers to the same array and you can take their difference.