Search code examples
c++stliteratorundefined-behaviorstdlist

Why does std::distance() for std:list<int>::iterator not return a negative number when last is before first?


std::distance is giving me a circular distance on std::list, not a relative distance. Why?

 #include <list>                                                                 
 #include <iostream>                                                             
 #include <iterator>                                                             

 using namespace std;                                                            

 int main(){                                                                     
     list<int> derp = {1,2,3,4};                                                 
     auto begin = derp.begin();                                                  
     auto end = derp.end();                                                      
     end--;                                                                      
     cout << distance(end, begin) << endl;                                       
     cout << distance(begin, end) << endl;                                       
}             

When I run this, the following output happens:

2
3

I expect the following:

-3
3

Why is this happening?


Solution

  • Your code has undefined behavior. For std::distance

    If InputIt is not LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first by (possibly repeatedly) incrementing first. If InputIt is LegacyRandomAccessIterator, the behavior is undefined if last is not reachable from first and first is not reachable from last.

    The iterator of std::list is not RandomAccessIterator, and its begin is not reachable from end by incrementing end.