【问题标题】:Empty list iterators comparison is always true空列表迭代器比较总是正确的
【发布时间】:2018-05-06 13:56:51
【问题描述】:

我正在使用以下代码测试空列表的列表迭代器:

代码

#include <iostream>
#include <list>


int main(){
    std::list<int> l;
    bool a, b, c;
    std::list<int>::iterator i = l.begin();
    a = i == --l.end();
    b = ++i == l.end();
    c = ++i == l.end();
    std::cout << a << std::endl;
    std::cout << b << std::endl;
    std::cout << c << std::endl;
}

结果

1
1
1

三个bool的结果总是正确的,但是我在增加和减少迭代器,为什么它们总是指向同一个地址

【问题讨论】:

  • --l.end(); 是带有空容器的 UB。

标签: c++ list iterator


【解决方案1】:

这只是未定义的行为,因为不允许您以使迭代器超出基础范围的方式递增或递减迭代器。

由于在这种情况下范围为空,因此您的所有三个操作都是非法且不正确的。

【讨论】:

    猜你喜欢
    • 2012-11-05
    • 1970-01-01
    • 2021-03-03
    • 2016-05-25
    • 2016-12-11
    • 2013-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多