列出迭代段错误

时间:2016-04-13 07:42:42

标签: c++ list stl iterator

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

这可以按预期工作!

但是,当我将列表的引用传递给antoher函数时:

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

我得到了一个段错误:-( 我试过没有使用引用或指针,但结果相同。 你对这个问题有所了解吗?

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

你正在尝试做什么没有任何问题,如下面的代码所示:

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

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

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