为什么 std::d istance() 对于 std:list:<int>:itrator 在 last 在 first 之前时不返回负数?

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

本文关键字:std first last 返回 int istance 对于 list gt 为什么 lt      更新时间:2023-10-16

std::distance给了我一个圆形std::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

如果InputIt不是LegacyRandomAccessIterator,则如果无法通过(可能重复(递增firstfirst访问last则行为未定义。如果InputItLegacyRandomAccessIterator,则如果无法从first访问last并且无法从last访问first则行为未定义。

std::list的迭代器不是 RandomAccessIterator,并且无法通过递增endend访问其begin

对于不满足随机访问迭代器要求的迭代器,std::distance返回first(第一个参数(必须递增到等于last(第二个参数(的次数。

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