1

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.

Paulo Neves
  • 1,096
  • 14
  • 22
  • 5
    Remove `std::prev` – Richard Critten Apr 20 '19 at 15:56
  • Could you elaborate on why my reasoning of using the std::prev is wrong? – Paulo Neves Apr 20 '19 at 15:57
  • 5
    Ranges in C++ are usually of half-open (i.e., `[begin, end)`). – Cornstalks Apr 20 '19 at 15:59
  • 1
    Per [this example](https://en.cppreference.com/w/cpp/iterator/distance), `std::distance(v.begin(), v.end()) == v.size())`. – Simon Doppler Apr 20 '19 at 16:00
  • @PauloNeves work through the example here: https://en.cppreference.com/w/cpp/iterator/distance – Richard Critten Apr 20 '19 at 16:01
  • Oh I think i figured it out. It has to do that the distance of iterators is not what I expected. @RichardCritten: They are number of increments. I think i can answer my question then. – Paulo Neves Apr 20 '19 at 16:03
  • The distance between a and b is the number of "unit steps" you need to take to get from a to b. This is the way measuring distance usually works. Same principle: if you put ten poles in the ground, one metre apart, the distance between the first pole and the last is nine metres, not ten. If you want to "measure" how many the poles are, you need to measure the distance from a to a (possibly imaginary) eleventh pole. – molbdnilo Apr 20 '19 at 16:10

1 Answers1

2

Suppose we have a list of size 1. Then l.end() is the [non-existent] 2nd element (index 1) and prev(l.end()) is the 1st element (index 0). Then std::distance(l.begin(), std::prev(l.end())) is 0, when it should be 1.

Steven Fontanella
  • 764
  • 1
  • 4
  • 16