以 QMap 做 sort

QMap 內的資料會以 key 的值 sort 好。以自訂 class 或 struct 作為 key 需要提供 operator<。所以將資料 insert 進 QMap,再用 iterator 取出就可以做到 sorting。

1
2
3
4
5
6
7
8
9
10
11
12
QMap<int, QString> sortMap;

sortMap.insert(31, "31");
sortMap.insert(3, "3");
sortMap.insert(2, "2");
sortMap.insert(5, "5");
sortMap.insert(7, "7");

for (QMap<int, QString>::iterator iter = sortMap.begin(); iter != sortMap.end(); ++iter)
{
// sorted
}

key 有多個欄位時可以做到不同欄位有不同 priority 的能力,如:

1
2
3
4
5
6
7
8
9
bool operator<(const XXX& rhs) const
{
if (fieldA != rhs.fieldA)
return fieldA < rhs.fieldA;
if (fieldB != rhs.fieldB)
return fieldB < rhs.fieldB;
...
return false;
}

這表示在比較上,fieldA 的 priority 比 fieldB 高,也就是先比 fieldA 再比 fieldB。

x < yy < x 都為 false 時表示 x == y