Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 649
Brandon Maness Avatar asked Sep 02 '20 15:09

Brandon Maness


People also ask

Can we subtract 2 iterators?

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.

Can I compare two iterators C++?

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 >, >=, <, <=.

What is the point of iterators?

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.


2 Answers

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.

like image 128
R Sahu Avatar answered Sep 19 '22 23:09

R Sahu


because it makes not much sense to do that operation, therefore there is no operator+ defined in the iterator

like image 33
ΦXocę 웃 Пepeúpa ツ Avatar answered Sep 20 '22 23:09

ΦXocę 웃 Пepeúpa ツ