列出迭代segfault
List iterating segfault
我在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
因此,几乎可以肯定的是,你尝试的方式有问题,如果你提供一个完整的例子,这将更容易帮助你。
我的建议是检查上面的代码并尝试理解它。然后你就可以弄清楚为什么你的代码表现不同了。
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 迭代时从向量和内存中删除对象
- 如何在c++迭代器类型中包装std::chrono
- 带过滤器的现代迭代c++集合
- 在c++中检查长方体是否尽可能快地重叠(无迭代)
- C++矢量迭代
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 擦除while循环中迭代的元素
- 实现一个在集合上迭代的模板函数
- 对于set上的循环-获取next元素迭代器
- 迭代时修改设置可让我segfault
- 迭代器:如果 '*' 返回元素的引用,为什么删除 *(myList.end()) 会给出 SegFault
- 怪异的迭代器行为+带有无序集的segfault
- 访问迭代器值会导致segfault 11
- 列出迭代segfault
- 取消迭代器时出现Segfault
- C++-映射迭代器访问导致segfault