PDA

View Full Version : sort a Qvector based on another Qvector



OzQTNoob
16th February 2012, 02:47
If i have a QVector<double> lets say vect1 with values of 30, 5, 3, 20 and I want to sort from low to high I can use qsort, but if I have a second QVector vect2 that is related to the first, and also has the same number of elements is there anyway for me to also sort the second vector vect2 based on how the first vector vect1 was sorted.

e.g. vect1 = [30, 5, 3, 20], vect2 = [0, 1, 2, 3] before sorting. After sorting vect1 = [3, 5, 20, 30] and ideally we would have vect2 as vect2 = [2, 1, 3, 0]

cheers
Oz

ChrisW67
16th February 2012, 04:46
Are the vectors particularly large? If not, the QMap approach described in the qSort docs might be suitable. Use vect1[i] as the key and vect2[i] as the value. The you get the vectors back using keys() and values():


QVector<double> v1;
QVector<int> v2;
v1 << 30 << 5.9 << 3.14 << 20.5 << 3.14;
v2 << 0 << 1 << 2 << 3 << 9;

QMap<double, int> sortMap;
for (int i = 0; i < v1.size(); ++i)
sortMap.insertMulti(v1.at(i), v2.at(i));

v1 = sortMap.keys().toVector();
v2 = sortMap.values().toVector();
qDebug() << v1;
qDebug() << v2;

You need to use insertMulti() to preserve duplicates.

OzQTNoob
16th February 2012, 07:39
Hi Chris,

The QVectors are typically very small and only have 10-30 entries per spectrum (they represent absorption feature locations for a given spectral sample), however there are 15K-100K spectra/samples in a given dataset e.g. they are QVector<QVector<double> > with the inner vector being the spectral feature results (10-30 entries) for the outer vector (15K-100K spectral samples).
The number of spectra doesn't really concern me though as I am quite happy for it to take a minute or so to loop over the spectral samples. I will have a play with the code you posted and look more closely at QMap.

Much appreciated.

I actually was wondering how to get rid of duplicates :) so now I know :)

Added after 1 38 minutes:

Hi Chris,

worked a treat and was able to put it in my continuum removal routine that is called on a per-spectrum basis anyway so I dont even think it slowed my code down. The 15K case doesnt even have time to stick up the progress dialog and the 100K case takes about 1 minute (both reading the data in and processing)

so muchos gracias amigo