遍历列表

发布于 2024-10-25 22:07:37 字数 722 浏览 7 评论 0原文

我试图一次遍历列表 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++ 列表的新手,如果这个问题听起来很愚蠢,我很抱歉

im trying to traverse through a list 2 values at a time, but for some reason, its getting stuck in an infinite loop

i have:

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++;
    }
}

say the combined list a is {1,2,3,3,4,5,6,6,6,7} and that i am trying to remove duplicates. i am trying to get *i = 1 and *j = 2 at first and then shift down so *i = 2 and *j = 3. what did i do wrong in this code??

im new to c++ lists, so sorry if this question sounds silly

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

凉薄对峙 2024-11-01 22:07:37

您需要使用 it2 = a.erase(it2); 否则 it2 将指向您已从列表中删除的元素。 a.erase 返回 it2 之后的元素。

You want to use it2 = a.erase(it2); otherwise it2 will be pointing to an element that you've erased from the list. a.erase returns the element following it2.

却一份温柔 2024-11-01 22:07:37

由于您的列表似乎已排序并且您想要删除重复项,因此请使用 unique

a.unique();

然后您不必混乱迭代器,擦除,等。

请参阅http://www.cplusplus.com/reference/stl/list/unique /

Since your list appears to be sorted and you want to remove duplicates, use unique:

a.unique();

Then you don't have to mess with iterators, erasing, etc.

See http://www.cplusplus.com/reference/stl/list/unique/

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文