我试图一次遍历列表 2 个值,但由于某种原因,它陷入了无限循环
我有:
list<mystruct> a, b; // defined, each guaranteed to have at least 1 value
a.insert(a.end(), b.begin(), b.end());
a.sort(mysort);
list<mystruct>::iterator it1 = a.begin(), it2 = it1// or = a.begin(), it doesnt seem to make a difference
it2++;
while(it2 != a.end()){// im not sure if this condition is correct; probably the error
if (<condition>){
// stuff
a.erase(it2);
}
else{
it1++;
it2++;
}
}
假设组合列表 a
是 {1,2,3,3,4,5,6,6,6,7}
并且我正在尝试删除重复项。我试图先得到 *i = 1 和 *j = 2,然后向下移动,所以 *i = 2 和 *j = 3。我在这段代码中做错了什么??
我是 C++ 列表的新手,如果这个问题听起来很愚蠢,我很抱歉
最佳答案
您想使用 it2 = a.erase(it2);
否则 it2 将指向您已从列表中删除的元素。 a.erase 返回它后面的元素2。
关于c++ - 遍历列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5424983/