【问题标题】:Why backward list iteration doesn't display node inserted before head of list?为什么向后列表迭代不显示在列表头之前插入的节点?
【发布时间】:2020-04-13 18:58:20
【问题描述】:

我正在为以下代码苦苦挣扎:

 list<int> numbers;
 numbers.push_back(1);
 numbers.push_back(2);
 numbers.push_back(3);
 numbers.push_front(0);


 list<int>::iterator it = numbers.begin();
 numbers.insert(it, 100); 

 for(list<int>::iterator it=numbers.begin(); it != numbers.end(); it++)
 {
    cout << *it << endl;
 }

输出>>100 0 1 2 3

但是当反向迭代时:

list<int>::iterator itBack = numbers.end();

for(; itBack != numbers.begin(); itBack--)
{
   cout << *itBack << endl;
}

输出>>5 3 2 1 0

那个 5 是从哪里来的?为什么没有编号为 100 的元素?

提前致谢

【问题讨论】:

  • 您有未定义的行为。您不能取消引用 numbers.end() 在第一次循环迭代时所做的事情。
  • 这不是你反向迭代的方式。你需要reverse_iterators
  • FYI -- 当在 Visual Studio 中运行时,此代码在向后 for 循环的第一行给出即时的 assert() 错误。错误是“无法取消引用结束迭代器”。所以你很幸运有任何输出出现。
  • 我已经使用 gcc 7.5 编译了它
  • 您必须使用反向迭代器:for(auto it = numbers.rbegin(); it != numbers.rend(); it++)。注意:end 迭代器指向列表中最后一个之后的“元素”(它不是有效元素)。 rend 迭代器指向第一个之前的“元素”(它又不是一个有效的元素)。由于上述原因,所有“*end”迭代器都不能被取消引用

标签: c++ linked-list stl


【解决方案1】:

您遇到的问题是end() is't 不会返回指向列表中最后一项的迭代器,而是指向最后一项后一个列表中的项目。这允许以下代码

for(list<int>::iterator it=numbers.begin(); it != numbers.end(); it++)

为列表中的每个项目运行,并且仅在迭代器指向列表末尾过去时退出...因此打印每个元素。 对于反向演员

itBack != numbers.begin()

这将变得不真实因为您到达列表的第一个元素,因此不会为它运行。正如 cmets 中提到的那样,试图遵循 end() 具有未定义的行为,因为您实际上是在数组外部进行索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-04
    • 2011-12-23
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多