Wednesday, 19 December 2012

Qt QMap - Sort by value

This is a demonstration of how to sort a QMap by value and not by key in qt c++. The values of the QMap were extracted and stored in a QList container object, then sorted through the qSort method. The keys were also stored in a QList for themselves. After sorting is complete, the QMap object is then cleared and the Keys and values are then inserted back in the QMap container in ascending order by value. See solution below: 

    #include <QCoreApplication>
    #include <qalgorithms.h>
    #include <QMap>
    #include <QDebug>
    #include <QList>
    
    
    int main(int argc, char *argv[])
    {
        QCoreApplication a(argc, argv);
        QMap <int, int> dataMapList;
        //QMap <int, int> sorted = new QMap<int, int>();
        QList <int> keys; // container to store all keys from QMap container
        QList<int> values; // container to store all values from QMap container
        QMap<int, int>::Iterator h; // used to loop/ iterate through QMap
    
        // used to iterate through QLists
        QList<int>::Iterator i; //
         QList<int>::Iterator j;
    
         //inserts to QMap Container
        dataMapList.insert(1,34);
        dataMapList.insert(3,2);
        dataMapList.insert(2,32);
        dataMapList.insert(14,89);
        dataMapList.insert(7,23);
    
        h=dataMapList.begin();
    
         qDebug()<< "unsorted";
        //list out the unsorted values along with their respective keys
        while(h!=dataMapList.end()){
            qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl;
            h++;
        }
    
    
        values = dataMapList.values(); // pass all values in the QMap to a QList container to store values only
        keys= dataMapList.keys(); // pass all keys in the QMap to a QList container to store already  sorted by default keys
    
        qSort(values); // sorts the values in ascending order
        dataMapList.clear(); // empties the QMap
    
        i=values.begin();
        j=keys.begin();
    
        // insert back the sorted values and map them to keys in QMap container
        while(i!=values.end() && j!=keys.end()){
    
            dataMapList.insert(*j, *i);
            i++;
            j++;
        }
    
    
        qDebug() << "sorted" << endl;
        h=dataMapList.begin();
        //the display of the sorted QMap
        while(h!=dataMapList.end()){
            qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl;
            h++;
        }
    
    
    
        return a.exec();
    }

No comments:

Post a Comment