QMap: Iterator and foreach



  • Hi.
    Here's my code;

    #include <QCoreApplication>
    #include <Qdebug>
    #include <QMap>
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
    
        QMap<int,QString> Employee;
    
        Employee.insert(1,"Bob");
        Employee.insert(2,"Chad");
        Employee.insert(3,"Marry");
        Employee.insertMulti(1,"Amy");
    
        foreach(int i, Employee.keys())
        {
            qDebug() << Employee[i];
        }
    
        QMapIterator<int,QString> Iter(Employee);
        while(Iter.hasNext())
        {
            Iter.next();
            qDebug() << Iter.key() << Iter.value();
        }
    
        return a.exec();
    }
    

    But the result is :
    "Amy"
    "Amy"
    "Chad"
    "Marry"

    1 "Amy"
    1 "Bob"
    2 "Chad"
    3 "Marry"

    So my question is:
    Why the results of "foreach" and "Iterator" is differet????
    I mean,why foreach makes two "Amy"??

    Thanks for helping !



  • Hi @ALLINXXX, welcome :)

    Employee.insert(1,"Bob");
    Employee.insertMulti(1,"Amy")
    

    Here you have two items under the key 1, so Employee.keys() returns 1 twice as per the docs:

    Keys that occur multiple times in the map (because items were inserted with insertMulti(), or unite() was used) also occur multiple times in the list.

    So then this line executes twice with i set to 1.

    qDebug() << Employee[i];
    

    Both times the [] operator just returns the last value associated with the key 1, as per the docs:

    If the map contains multiple items with key key, this function returns a reference to the most recently inserted value.

    Cheers.



  • @Paul-Colby
    Appreciate!
    One one Question ,How to turn "UNSOLVED" question to solved question
    thanks! (^o^)/


  • Qt Champions 2016



  • @kshegunov
    Thanks!
    The forum is nice for rookies!


  • Banned

    This post is deleted!

Log in to reply
 

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