iterator expected to have different behaviour when calling next()/previous() on items



  • I have created a simple map and an iterator on it. When i move the iterator to next items, it performs well. After forwarding the iterator, if I ask it to go back for previous item and get value() of the iterator, it is not really the previous item value and actually the value is not changed at all. It seems there is something wrong or maybe I'm using it in a wrong way! Where is the problem?

    see the below code

    #include "mainwindow.h"
    #include <QApplication>
    #include <QMap>
    #include <qiterator.h>
    
    int main(int argc, char *argv[])
    
    {
        QApplication a(argc, argv);
    
    QMap<double,int> map;
    map.insert(4234,3);
    map.insert(4200,2);
    map.insert(4100,1);
    map.insert(4000,0);
    
    QMapIterator<double, int> i(map);
    i.toFront();
    
    i.next();
    i.next();
    int va1 = i.value();    // val1 is 1 as expected
    
    i.previous();
    
    int val2 = i.value(); // It is expected that val2 should be 0 but is still Surprisingly 1!!!!
    
    return a.exec();
    }
    


  • form http://doc.qt.io/qt-5/qmapiterator.html

    The first call to next() advances the iterator to the position between the first and second item, and returns the first item;

    so first call to next returns the first item (0), the second call returns the second item (1) the first call to previous returns the first item again (1)

    using this image:
    Java Iterator Image

    next and previous return the item they jumped over so if you call next 1 time it returns A as it jumps over A, the second time it jumps over B, if you then call previous it jumps over B again so it returns b again


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.