rotating_image
rotating_image

Reputation: 3086

STL iterator in Qt

i want to traverse a list and delete elements greater than 30

QList<double> mylist;
QList<double>::iterator myiterator = mylist.begin();

mylist.append(6);
mylist.append(36);

myiterator=mylist.begin();
while(myiterator!=mylist.end())
{
    if(*(myiterator)>30)
    {
        QList<double>::iterator next=myiterator;
        next++;
        mylist.erase(myiterator);
        myiterator=next;

    }
    else
        myiterator++;

    if(myiterator==mylist.end())
        std::cout<<"end of list "<<std::endl;
    else
        std::cout<<" not end of list "<<std::endl;
}

output is

 not end of list 
 not end of list 
The program has unexpectedly finished.
/home/maverik/Desktop/Qt/container_class/container_class exited with code 0

where as if i make mylist = {36,34} or mylist = {36,9} or mylist={9,10} then output is

 not end of list 
end of list 

the error only comes when the last element is greater than 30 or if greater but the 1st element is also greater than 30

Upvotes: 0

Views: 721

Answers (2)

mfontanini
mfontanini

Reputation: 21910

You are advancing your iterator twice when you delete an element, here's the fix:

QList<double>::iterator next=myiterator;
myiterator++;
mylist.erase(next);

That should be done when *myiterator > 30

EDIT: actually, QList::erase returns an iterator to the next element. Therefore, this code should do it:

myiterator = mylist.erase(myiterator);

Upvotes: 2

edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31951

Like the C++ standard containers erase returns an iterator to the element after the deleted one, so that part of your loop should be quite simple:

 if((*myiterator)>30)
    myiterator = mylist.erase( myiterator );
 else
    myiterator++;

Upvotes: 4

Related Questions