Search code examples
c++iteratoroperator-overloadingstdvectorpointer-arithmetic

Why can two std::vector iterators not be summed?


This is more of a curiosity question about C++ that came up after learning how to find the index referenced by an iterator.

Given two vector iterators, why can they be subtracted from each other but not added together?

For instance, why does this compile and run:

std::vector<int> vect;
vect.begin() - vect.end();

While this does not:

std::vector<int> vect;
vect.begin() + vect.end();

The question is the get a better concept of how iterators behave. For those that commented and answered, thank you! I need to look more into pointer arithmetic to understand this.

The answer I think helped the most was that iterators are like pointers.

Subtracting two pointers to get the difference in their distance makes sense, just like looking at 1-10 on a number line and wanting the distance between 7 and 3, you subtract 7 from 3 for a distance of 4.

Adding 7 and 3 gives 10, which doesn't help me find the distance between them and, in a container, will end up pointing to something outside the container's bounds, which is not helpful or useful.


Solution

  • Iterators are modelled after pointers.

    Given pointers P1 and P2, the expression P2 - P1 gives you the offset/distance between the pointers. There is nothing sensible you can expect from the expression P1 + P2. Extend that idea to iterators and you will understand why subtraction between two iterators makes sense but addition does not.