I am finding a behavior that I would like to understand better.
I have an std::list<int> l;
with N elements, where N>0 (non-empty).
I then compared the std::distance
between the l.begin()
and std::prev(l.end())
. I was expecting this to be equal to l.size()
because l.end()
is an iterator that does not exist, and thus should not be accounted for in the distance.
In code form, why:
l.size() != std::distance(l.begin(), std::prev(l.end())
Edit on why this is not a duplicate
This question is not related to this question on intervals because my question is about the nature of distance
of iterators not on the nature of l.begin()
and l.end()
intervals, although useful and related concepts. I clearly stated that I used prev(l.begin())
and stated why.
Given the comments in the question, I understood my conceptual error and I was going to post and answer saying that there is no guarantee that distance()
will give you size()
, because distance
count The number of increments needed to go from first to last passed iterator, not the number of elements in a given interval. Given that the question was blocked by the deduplicator I could not answer what I think is the proper answer and add an example.