laura
laura

Reputation: 2135

Qt C++ Modifying an object from a list while iterating

I want to modify the original content of a list object while i'am iterating the list. I've been trying this using 2 ways: first one -> using a for loop -> which is working properly, but i am not sure that is the best option, and the second one using QMutableListIterator which is not changing at all the object and i thought that maibe i am not using it corectly. Below there are my 2 implementations.

first one

 QString idNumber = getIDNumberFromSelectedRow(id);
 QUuid carId = QUuid(idNumber);
    for(int i = 0; i < cars.size(); i++){
        Vehicle& current = cars[i];
        if(carId == current.getVehicleID()){
            addDialog = new AddEditDialog(this);
            addDialog->loadVehicleToEdit(current); // i am loading the data from the object i want to edit
            addDialog->exec();
            if(addDialog->getIsEdited()){ //i'm editing the object
                current = addDialog->getVehicleToAdd(); //i'm saving the modifications
                current.setVehicleId(carId);
            }
        }//the object from the list is now modified
    }

second one

 QMutableListIterator<Vehicle> iterator(cars);
 while(iterator.hasNext()){
        Vehicle& current = iterator.next();
        if(carId == current.getVehicleID()){
            addDialog = new AddEditDialog(this);
            addDialog->loadVehicleToEdit(current); //load the object data to modify
            addDialog->exec();
            if(addDialog->getIsEdited()){//edit the object
                current = addDialog->getVehicleToAdd();//save the modifications
                iterator.setValue(current);
            }
        }//the object from the list is not modified at all
    }

Upvotes: 2

Views: 1143

Answers (2)

CapelliC
CapelliC

Reputation: 60004

QMutableListIterator is meant to modify the list while you're iterating, for instance inserting/removing items. Then it's not the right tool for your task. Indeed, the documentation states that when you call next(), the iterator points to the successive element. Maybe it's this detail that inhibits your changes to appear as expected.

From docs:

T & QMutableListIterator::next () Returns a reference to the next item, and advances the iterator by one position.

Upvotes: 1

Boris Dalstein
Boris Dalstein

Reputation: 7748

Your first method is really fine, nothing to worry about :-) In Qt, a QList<T> is not a linked list like std::list<T>, but a container that gives you average constant time for access.

If you still want to use an iterator, do not use QMutableListIterator<Vehicle>, but QList<Vehicle>::iterator.

Upvotes: 1

Related Questions