为什么 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::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,则如果无法通过(可能重复(递增first
从first
访问last
则行为未定义。如果InputIt
是LegacyRandomAccessIterator,则如果无法从first
访问last
并且无法从last
访问first
则行为未定义。
std::list
的迭代器不是 RandomAccessIterator,并且无法通过递增end
从end
访问其begin
。
对于不满足随机访问迭代器要求的迭代器,std::distance
返回first
(第一个参数(必须递增到等于last
(第二个参数(的次数。
您正在使用没有随机访问迭代器的std::list
。在distance(end, begin)
的情况下,无论你递end
多少倍,它永远不会等于begin
。因此,行为是未定义的,结果取决于标准库实现的细节。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++17复制构造函数,在std::unordereded_map上进行深度复制
- 如何导出包含具有"std::unique_ptr"值的"std::map"属性的
- 从持续时间构造std::chrono::system_clock::time_point
- std::具有相同基类的类的变体
- std::向量与传递值的动态数组
- 使用std::vector的OpenCL矩阵乘法
- 为什么 std::set.erase(first, last) 会影响从中获取 (first, last) 的容器?
- 为什么 std::d istance() 对于 std:list:<int>:itrator 在 last 在 first 之前时不返回负数?
- c std :: vector迭代器构造函数,first == last
- 为什么 std::find_if(first, last, p) 不通过引用获取谓词?
- 我怎样才能保持'first'和'second'用结构替换 std::p air?
- 自定义迭代器中distance_type的目的 - std::d istance(first, last) 将返回错误的
- 是否可以在C++中使用命名变量(例如,键和值)而不是 .first 和 .second 进行 std::map<> "for element : container" 迭代?
- std::set<pair<int,int> > -- 仅使用 pair<>::first 作为键查找
- boost::transform_iterator 不适用于 std::bind( &Pair::first, _1 )?
- std::remove_reference or std::remove_cv first?
- 我可以使用std::pair,但是重命名.first和.second成员名吗?