当前位置: 动力学知识库 > 问答 > 编程问答 >

c++ - traversing through a list

问题描述:

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

网友答案:

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.

网友答案:

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/

分享给朋友:
您可能感兴趣的文章:
随机阅读: