6

I wonder whether their is some algorithm in stl or in Qt that sorts an array of double and return the indices of sorted items in the original list. Eg. L = 1 , 2 , 5 , 3 L_sort = 1 , 2 , 3 , 5 Indices = 1, 2 , 4, 3

So that I can afterwards calculate AnotherList[Indices] (the same order prevails in both lists, with respect to the original list L).

In the end, I thought of creating a QList, each MyStruct containing two members, one of same type LType as elements in L, the other of same type AnotherType as elements in AnotherList. And then ordering with respect to members of type LType. However I have this idea, I don't know properly how to proceed in Qt.

Thanks and regards

4

1 に答える 1

9

インデックス付きのデータをペアで保存できます...最初は値で並べ替え、2番目はインデックスで並べ替えます...

QList<QPair<LType,int> > array;
for (int i = 0; i < 100; i++)
{
    LType x = ...
    array.append(qMakePair(x,i));
}

// Ordering ascending
qSort(array.begin(), array.end(), QPairFirstComparer());

.....

// Restoring start order
qSort(array.begin(), array.end(), QPairSecondComparer());

これらのクラスが必要です:

struct QPairFirstComparer
{
    template<typename T1, typename T2>
    bool operator()(const QPair<T1,T2> & a, const QPair<T1,T2> & b) const
    {
        return a.first < b.first;
    }
};

struct QPairSecondComparer
{
    template<typename T1, typename T2>
    bool operator()(const QPair<T1,T2> & a, const QPair<T1,T2> & b) const
    {
        return a.second < b.second;
    }
};
于 2012-04-17T10:39:07.840 に答える