【问题标题】:List iterating segfault列表迭代段错误
【发布时间】:2016-04-13 07:42:41
【问题描述】:

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

我得到一个段错误:-( 我尝试不使用引用或使用指针,但结果相同。 你对这个问题有什么想法吗?

感谢您的帮助!

【问题讨论】:

  • 好吧,首先,你的函数中没有MyAucList;参数为MyListMyAucList 到底是从哪里来的?发一个real MCVE.
  • @WhozCraig : 哦,对不起,我在编辑我的帖子时犯了一个错误,我编辑它!
  • 太好了,现在请注意该评论的第二部分。我可怜的廉价玻璃仿水晶球告诉我Auction 正在打破Rule of Three,但没有MCVE 就不可能确定。我们不是介意读者。在调试器中运行它可能会准确地告诉你车轮从哪里掉下来。
  • 展示问题的完全独立的程序应该是您的首要任务,并且通常应该在提出问题之前完成。通常,它会让事情变得如此明显,你不会需要问:-)
  • 感谢您的建议,我会这样做的!

标签: c++ list stl iterator


【解决方案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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-29
    • 2013-11-10
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-10
    • 1970-01-01
    相关资源
    最近更新 更多