遍历列表
我试图一次遍历列表 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要使用
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.由于您的列表似乎已排序并且您想要删除重复项,因此请使用
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/