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.
If two unrelated iterators (including pointers) are subtracted, the operation results in undefined behavior [ISO/IEC 14882-2014]. Do not subtract two iterators (including pointers) unless both point into the same container or one past the end of the same container.
we can use == and != to compare to valid iterators into any of the library containers. The section also tells us that iterators for string and vector support relational operators (aka iterator arithmetic) which include >, >=, <, <=.
The primary purpose of an iterator is to allow a user to process every element of a container while isolating the user from the internal structure of the container. This allows the container to store elements in any manner it wishes while allowing the user to treat it as if it were a simple sequence or list.
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.
because it makes not much sense to do that operation, therefore there is no operator+
defined in the iterator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With