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.
(x + y) / 2
is tractable. Alas it needs to be written asx + (y - x) / 2
, which is not as clear and relies on second term being an interval. – Trainloadx + y
is always meaningless. It isn't. You do make a very important point about pointer arithmetic being only valid within arrays (and 1 past the end). – Trainload