我在使用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


因此,几乎可以肯定,您尝试执行此操作的方式存在问题,如果提供了完整的示例,则可以更轻松地为您提供帮助。

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

09-10 05:24
查看更多