# Thread: Sorting algorithm to sort data based on common keys

1. Intermediate user
Join Date
Jun 2015
Posts
86
Thanks
20
Qt products
Platforms

## Sorting algorithm to sort data based on common keys

Hi,

I have data in a format like as,
Qt Code:
1. QList<QPair<QString, QJsonValue>> sessionList
To copy to clipboard, switch view to plain text mode

Check the sample data of sessionList
QPair("2717b2bb-aa1f-460e-b6ff-c932114a8b99",QJsonValue(object, QJsonObject({"CreatedAt":"2019-06-18T10:34:37.3501135","FileName":"imgLeft8bitColor_ 000000050.png","FrameIndex":30,"ImageGuid":"76d453 ed-0950-424d-952f-b20d1f0c921f","IsKeyframe":false, "TabGuid":"2717b2bb-aa1f-460e-b6ff-c932114a8b99"})))
Like above I have more data that I want to sort based on QPair.first(consider as key)(say, "078f7119-844d-4c31-9eee-c695f2c9adbb").
So what sorting algorithm I should use which sort my QJsonValue for the same type of key in one container?

Note: Key count can vary

Join Date
Jul 2008
Posts
406
Thanks
9
Thanked 52 Times in 50 Posts
Qt products
Platforms

## Re: Sorting algorithm to sort data based on common keys

Hi, you can use std::sort to sort a QList. This algorithm accepts a custom compare function.
See http://www.cplusplus.com/reference/algorithm/sort/ for details and an example.

Ginsengelf

3. Intermediate user
Join Date
Jun 2015
Posts
86
Thanks
20
Qt products
Platforms

## Re: Sorting algorithm to sort data based on common keys

Sorting means not to sort in ascending or descending order, I want all the data having the same key in one container.
I found one solution for that, use QMultiHash or QMultiMap, here it can allow adding multiple data under the same key, so in that way, I can distinguish or sort data.

But still, I'm looking for an option where I can have one key and data can be added under that key only, not the way QMultiHash work, as it stores key and data in a separate list even if keys are same.
Last edited by npatil15; 20th June 2019 at 07:41.

Join Date
Jul 2008
Posts
406
Thanks
9
Thanked 52 Times in 50 Posts
Qt products
Platforms

## Re: Sorting algorithm to sort data based on common keys

Maybe a QMap < QString, QList < QJsonValue > >?

Ginsengelf

5. ## The following user says thank you to Ginsengelf for this useful post:

npatil15 (20th June 2019)

6. Intermediate user
Join Date
Jun 2015
Posts
86
Thanks
20
Qt products
Platforms

## Re: Sorting algorithm to sort data based on common keys

Thank you Ginsengelf, it works like a charm