gpt4 book ai didi

c++ - 列出迭代段错误

转载 作者:行者123 更新时间:2023-11-28 05:44:03 25 4
gpt4 key购买 nike

我对 C++ 中的列表操作有疑问,请宽容我,我是这门语言的初学者。

所以,我有一个这样创建的列表:

list<Auction> MyAucList;

我构建了一些对象并将它们放入列表中:

Auction test(a, i); // a and i are int
MyAucList.push_back(test); // I put my objects in the list

现在,在同一个函数中,我可以迭代列表并从对象中获取数据:

for (list<Auction>::const_iterator it1 = MyAucList.begin(); it1 != MyAucList.end(); ++it1)
{
if ((*it1).Getitem() == 118632)
cout << "FOUND !" << endl;
}

这按预期工作!

但是,当我将对列表的引用传递给另一个函数时:

listHandling(MyAucList);
}

void listHandling(list<Auction> &MyAucList)
{
for (list<Auction>::const_iterator it1 = MyAucList.begin(); it1 != MyAucList.end(); ++it1)
{
if ((*it1).Getitem() == 118632)
cout << "FOUND : " << 118632 << endl;
}
}

我遇到段错误:-(我尝试不使用引用或指针,但结果相同。你知道这个问题吗?

感谢您的帮助!

最佳答案

您尝试做的没有问题,如下代码所示:

using namespace std;
#include <iostream>
#include <list>

class Auc {
private: int myX;
public: Auc (int x) { myX = x; }
int GetItem () { return myX; }
};

void listHandle (list<Auc> y) {
for (list<Auc>::const_iterator it = y.begin(); it != y.end(); ++it) {
cout << ((Auc)*it).GetItem() << endl;
if (((Auc)*it).GetItem() == 42)
cout << " Found 42\n";
}
}

int main () {
list<Auc> x;
Auc a(7); x.push_back(a);
Auc b(42); x.push_back(b);
Auc c(99); x.push_back(c);
Auc d(314159); x.push_back(d);

for (list<Auc>::const_iterator it = x.begin(); it != x.end(); ++it) {
cout << ((Auc)*it).GetItem() << endl;
if (((Auc)*it).GetItem() == 42)
cout << " Found 42\n";
}

cout << "===\n";

listHandle(x);
}

无论是在同一个函数中完成还是通过调用不同的函数完成,这都非常愉快地打印出数据:

7
42
Found 42
99
314159
===
7
42
Found 42
99
314159

因此几乎可以肯定,您尝试执行此操作的方式有问题,如果您提供一个完整的示例,将更容易为您提供帮助。

我的建议是检查上面的代码并尝试理解它。然后您可以弄清楚为什么您所拥有的东西表现不同。

关于c++ - 列出迭代段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36591740/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com