1

整数のリストをランダムに生成し、これらの値を QMap に入力しましたが、値でソートされた QMap を取得したいと思います

4

3 に答える 3

4

QMap <int, int>これは、 qt C++ でキーではなく値でソートする方法のデモです。

QMap の値が抽出され、QList コンテナー オブジェクトに格納され、qSort メソッドで並べ替えられました。キーは、それ自体の QList にも格納されていました。並べ替えが完了すると、QMap オブジェクトがクリアされ、キーと値が値の昇順で QMap コンテナーに挿入されます。以下の解決策を参照してください。

#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();
}

注: QMap と QList のイテレータは、格納されている値やキーにアクセスするためにコンテナをトラバースするために使用されました。これらは、リスト内のアイテムを表示するのにも役立ちました (ソートされていないものとソートされているもの)。このソリューションは、Qt コンソール アプリケーションで実行されました。

于 2012-11-20T06:45:20.070 に答える
3

QMapデフォルトでは、アイテムは常にキーでソートされます。したがって、次のように繰り返すQMapと:

 QMap<int, int>::const_iterator i = yourQMap.constBegin();
 while (i != yourQMap.constEnd()) {
     cout << i.key() << ": " << i.value() << endl;
     ++i;
 }

キーでソートされた結果が得られます。

標準アルゴリズムに適合するようにタスクを変換することを考えてみてください。それ以外の場合は、このアプローチを使用してタイトルを並べ替えることができます。

QList<int> list = yourQMap.values();
qSort(list.begin(), list.end());

そして、必要に応じて、 method を呼び出して関連付けられたキーを取得しますQMap::key(const T &value);

于 2012-11-20T00:07:03.710 に答える