【发布时间】:2020-02-09 20:54:15
【问题描述】:
正如我在问题中所说,我试图在屏幕上显示已创建对象的值,但输出是下面的循环而不是列表本身。
我已经使用函数list.begin() 来检查列表是否正确并有效地显示1,所以我不明白为什么for 循环中的值不正确。
总之,我没有发现错误,所以我想问你我哪里错了。
提前致谢。
#include <iostream>
#include <list>
using namespace std;
class Algo{
private:
list <int> l;
public:
Algo() {l = {1, 2, 3, 4, 5};}
list <int> getList() {return l;}
};
int main()
{
Algo a;
list <int>::iterator it;
it = (a.getList().begin());
for(it; it != (a.getList().end()); it++)
{
cout << *it << "\n";
}
}
预期输出:1,2,3,4,5
实际输出:1
-1952806520
16122456
-1228957360
1
-1952806520
16122456
-1228957360
1(无限循环)
【问题讨论】:
-
更重要的是,没有答案中提到的更改
it=(a.getList().begin());获取一个迭代器到 temporarylist<int>。该列表很快就消失了,留下一个 dangling 迭代器,使用它会调用 undefined behavior。