列出迭代segfault

List iterating segfault

本文关键字:segfault 迭代      更新时间:2023-10-16

我在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;
     }
}

我得到了一个segfault:-(我尝试不使用引用,也不使用指针,但结果相同。你对这个问题有想法吗?

谢谢你的帮助!

您尝试做的没有任何问题,以下代码证明了这一点:

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 42n";
    }
}
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 42n";
    }
    cout << "===n";
    listHandle(x);
}

无论是在同一个函数中还是通过调用不同的函数(),这都能很好地打印出数据

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

因此,几乎可以肯定的是,你尝试的方式有问题,如果你提供一个完整的例子,这将更容易帮助你。

我的建议是检查上面的代码并尝试理解它。然后你就可以弄清楚为什么你的代码表现不同了。