Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting algorithm with Qt/C++ - sort a QList of struct

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

like image 709
kiriloff Avatar asked Apr 17 '12 09:04

kiriloff


1 Answers

You can store data with indexes in pairs... First sort by values, second sort by indexes...

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

You just need these classes:

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;
    }
};
like image 183
k06a Avatar answered Nov 07 '22 15:11

k06a