Results 1 to 3 of 3

Thread: sort a Qvector based on another Qvector

Hybrid View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Join Date
    Feb 2012
    Location
    Australia
    Posts
    39
    Thanks
    15
    Thanked 4 Times in 3 Posts
    Qt products
    Qt4
    Platforms
    Windows

    Default sort a Qvector based on another Qvector

    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

  2. #2
    Join Date
    Mar 2009
    Location
    Brisbane, Australia
    Posts
    7,729
    Thanks
    13
    Thanked 1,610 Times in 1,537 Posts
    Qt products
    Qt4 Qt5
    Platforms
    Unix/X11 Windows
    Wiki edits
    17

    Default Re: sort a Qvector based on another Qvector

    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():
    Qt Code:
    1. QVector<double> v1;
    2. QVector<int> v2;
    3. v1 << 30 << 5.9 << 3.14 << 20.5 << 3.14;
    4. v2 << 0 << 1 << 2 << 3 << 9;
    5.  
    6. QMap<double, int> sortMap;
    7. for (int i = 0; i < v1.size(); ++i)
    8. sortMap.insertMulti(v1.at(i), v2.at(i));
    9.  
    10. v1 = sortMap.keys().toVector();
    11. v2 = sortMap.values().toVector();
    12. qDebug() << v1;
    13. qDebug() << v2;
    To copy to clipboard, switch view to plain text mode 
    You need to use insertMulti() to preserve duplicates.

  3. The following user says thank you to ChrisW67 for this useful post:

    OzQTNoob (16th February 2012)

Similar Threads

  1. Using Qwt with QVector
    By OzQTNoob in forum Qwt
    Replies: 3
    Last Post: 9th February 2012, 08:17
  2. Replies: 5
    Last Post: 2nd September 2011, 23:11
  3. Simple QVector sort?
    By bizmopeen in forum Newbie
    Replies: 3
    Last Post: 16th February 2010, 17:50
  4. Qvector
    By phillip_Qt in forum Qt Programming
    Replies: 3
    Last Post: 27th November 2007, 10:46
  5. QVector
    By sabeesh in forum Qt Programming
    Replies: 2
    Last Post: 17th September 2007, 14:37

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Qt is a trademark of The Qt Company.