为什么 std::distance() for std:list<int>::iterator 不是 return 当 last 在 first 之前时的负数?

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

std::distancestd::list 上给我一个圆距离,而不是相对距离。为什么?

 #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;                                       
}             

当我运行这个时,会发生以下输出:

2
3

我期望如下:

-3
3

为什么会这样?

您的代码有未定义的行为。对于 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.

std::list 的迭代器不是 RandomAccessIterator,它的 begin 无法通过递增 endend 到达。

对于不满足random access iterator, std::distance returns 要求的迭代器,first(第一个参数)的次数必须增加到等于last(第二个参数)。

您正在使用 std::list,它没有随机访问迭代器。在 distance(end, begin) 的情况下,无论您将 end 递增多少次,它都永远不会等于 begin。因此,行为是未定义的,结果取决于标准库实现的细节。