开发者

traversing through a list

开发者 https://www.devze.com 2023-02-19 08:11 出处:网络
im trying to traverse through a list 2 values at a time, but for some reason, its getting stuck in an infinite loop

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,开发者_C百科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/

0

精彩评论

暂无评论...
验证码 换一张
取 消