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?
Your code has undefined behavior. For std::distance
If
InputIt
is not LegacyRandomAccessIterator, the behavior is undefined iflast
is not reachable fromfirst
by (possibly repeatedly) incrementingfirst
. IfInputIt
is LegacyRandomAccessIterator, the behavior is undefined iflast
is not reachable fromfirst
andfirst
is not reachable fromlast
.
The iterator of std::list
is not RandomAccessIterator, and its begin
is not reachable from end
by incrementing end
.