PDA

View Full Version : How to sort a Qlist AND get a sort key?



agerlach
26th July 2010, 19:20
Howdy,

I have a several Qlists of equal length. Of those one contains a correlation value that I need to sort all of the Qlists on. I would like to get a sort key for the correlation Qlist that indicates its index in the unsorted correlation Qlist that can be used to access values in the other Qlist.

If A is the unsorted correlation list and B is the sorted correlation list, the sort key IX should result in
A[IX[i]] = B[i];


I am porting code from MATLAB to QT and this functionality is build directly in MATLAB's sort() function. The MATLAB documentation for sort() can be found here (http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sort.html).

This seems like it should be a routine thing. Does anybody have any suggestions?

franz
26th July 2010, 19:31
I would define a struct that contains the elements that you want to link together. You can put those into a single QList. If you define the < (less than) operator correctly, then you should have your sorted list without having the need for a translation to the old location.

agerlach
26th July 2010, 19:35
That is true, but I guess I was a little misleading with my wording. I would prefer to not actually sort the lists for various reasons other than the single correlation list.

franz
26th July 2010, 19:44
Chances are someone else wrote some function that does that for you. Else you would have to write it yourself. I'm pretty sure qSort() doesn't do that for you.

There's always the possibility of the struct I mentioned before, but only containing the thing you want to sort on and an integer. You copy the list, fill the integers with the original index and sort the new list based on your criteria. You can return just the list of integers if you prefer.

Maybe it still doesn't suit your needs, but I'll give you a jump start on my idea.

-- spoiler --


struct SortItem
{
QString itemToSort;
int origIndex;

bool operator<(const SortItem &other) const
{
return itemToSort < other.itemToSort;
}
};


// ...
QList<SortItem> items;
// fill the list
QList<SortItem> sortedItems = items;
qSort(sortedItems);
// run through sortedItems and get the origIndex to reference the item in the original lists.