c++ - 遍历列表

标签 c++ list conditional-statements infinite-loop

我试图一次遍历列表 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/

相关文章:

c++ - 什么是 C++ 和 VScode 中的#pragma 区域?

list - WinBugs的“Expected collection operator c”错误

Python:使用并行列表对列表进行排序

list - Prolog:找出所有列表元素的总和是否等于 N

cakephp - 使用hasMany模型查找条件

python - 我怎样才能制造多重不等式?

c++ - 为什么没有在范围内声明字符串

c++ - OpenCV:基于三角选择倾斜图像

c++ - 在 gtest 中将两个数组作为参数传递

javascript - React - 条件 JSX 渲染