Search code examples
c++vectoriterator

How does the subtraction of two iterators denote the index of a vector item in C++?


In a blogpost of GeeksForGeeks, subtraction of two iterators has been used to denote the index of a vector. Link of that post:

std::find in C++

I have also seen a related answer in stackoverflow:

How to convert vector iterator to int in C++

But it didn't describe the mechanism with a good example, so I am confused about this. Because, I can't print the iterators v.begin() and it separately while I can print the subtraction value of them which is ( it - v.begin() ).

So, how does that subtraction denotes the index of a vector item?


Solution

  • Subtracting one RandomAccessIterator from another gives the distance between them, because that's what operator- is defined to do for random access iterators.

    If you subtract begin() from another iterator, you get the distance from the beginning of the container to the second iterator, which is naturally the same value as the index of the element referenced by the second iterator.

    Using std::distance() instead of the operator overload is more flexible, and possibly clearer.

    All this stuff is documented and should be covered in a decent book.