Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

Struggling with a for loop



  • Hi,
    Sorry for this silly question but i spent more than 2 hours without success

    My problem is :
    i have a QList of items, the number of items is a multiple of a variable nbrOperationToRepeat
    items have a method setPosX(int)

    so lets say nbrOperationToRepeat = 3;
    and i have 9 items

    i want to iterate over the list and call setX() every 3 (nbrOperationToRepeat) items,

    so the x of my items should be :

    item.at(0) > 0
    item.at(1) > 0
    item.at(2) > 0

    item.at(3) > 1
    item.at(4) > 1
    item.at(5) > 1

    item.at(6) > 2
    item.at(7) > 2
    item.at(8) > 2

    i feel like this sould be an easy task, but i'm not able to do it right now, can someone please help with this ?

    for (int i = 0; i < finalOperationList.count(); i+=nbrOperationToRepeat ){ // finalOperationList.count() returns the number of items in the list
    
                    for(int j = 0; j < nbrOperationToRepeat; j++){
                          qDebug()<< "edit at: " << i+j;
                           finalOperationList.at(i+j)->setPosX(/*?*/); // cant figure out what to put here.. 
                    }
                }
    

    thank you


  • Lifetime Qt Champion

    @LeLev

    for (int i = 0; i < finalOperationList.count() / nbrOperationToRepeat; i++){
         for(int j = i * nbrOperationToRepeat; (j < i + nbrOperationToRepeat) && (j < finalOperationList.count()); j++){
             qDebug()<< "edit at: " << j;
             finalOperationList.at(j)->setPosX(i);
         }
     }
    

  • Moderators

    @LeLev said in Struggling with a for loop:

    for (int i = 0; i < finalOperationList.count(); i+=nbrOperationToRepeat ){ // finalOperationList.count() returns the number of items in the list
    
                    for(int j = 0; j < nbrOperationToRepeat; j++){
                          qDebug()<< "edit at: " << i+j;
                           finalOperationList.at(i+j)->setPosX(i / nbrOperationToRepeat); //if nbrOperationToRepeat is a int and not a double or float
                    }
                }
    


  • @jsulm , @J-Hilk ,

    Thank you very much for your inputs much appreciated



  • @LeLev said in Struggling with a for loop:

    I would work with modulus operator:

    for (int i = 0; i < finalOperationList.count();  ++i){
       int operationTodo = i % nbrOperationToRepeat;
       qDebug()<< "edit at: " << i << "and set:" << operationTodo ;
       finalOperationList.at(i)->setPosX(operationTodo);
    }
    

Log in to reply