Col*_*ell 4 c++ iterator stl stdlist undefined-behavior
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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行它时,会发生以下输出:
2
3
Run Code Online (Sandbox Code Playgroud)
我期望以下内容:
-3
3
Run Code Online (Sandbox Code Playgroud)
为什么会这样?
您的代码具有未定义的行为。为了std::distance
如果
InputIt不是LegacyRandomAccessIterator,如果last无法first通过(可能重复) incrementing到达,则行为未定义first。如果InputIt是LegacyRandomAccessIterator,则行为是未定义的,如果last不能从first并且first不能从 到达last。
的迭代器std::list不是 RandomAccessIterator,并且begin无法end通过递增来访问它end。