qStableSort 是否保留等效元素的顺序?
Does qStableSort preserve order of equivalent elements?
假设我有 QList 个按特定顺序插入的 100 MyItem
个对象。每个 MyItem
都有一个关联的 timestamp
和一些 属性 p
,不能保证是唯一的。
struct MyItem {
enum MyProperty { ONE, TWO, THREE };
double timestamp; //unique
MyProperty p; //non-unique
bool operator<(const MyItem& other) const {
return p < other.p;
}
};
假设我按时间顺序添加了 100 个对象,如果我在那个容器上 运行 qStableSort(从而按 p
排序),我是否可以保证一个给定的值p
,他们仍然按时间顺序排列?
https://en.wikipedia.org/wiki/Category:Stable_sorts
Stable sorting algorithms maintain the relative order of records with equal keys (i.e. values). That is, a sorting algorithm is stable if whenever there are two records R and S with the same key and with R appearing before S in the original list, R will appear before S in the sorted list.
因此 qStableSort
中的关键字 stable 正是指您所要求的。
但是请注意,qStableSort
是 obsoleted in Qt 5.5
Use std::stable_sort instead.
Sorts the items in range [begin, end) in ascending order using a stable sorting algorithm.
If neither of the two items is "less than" the other, the items are taken to be equal. The item that appeared before the other in the original container will still appear first after the sort. This property is often useful when sorting user-visible data.
根据 Qt 文档,您应该更喜欢使用 std::stable_sort
假设我有 QList 个按特定顺序插入的 100 MyItem
个对象。每个 MyItem
都有一个关联的 timestamp
和一些 属性 p
,不能保证是唯一的。
struct MyItem {
enum MyProperty { ONE, TWO, THREE };
double timestamp; //unique
MyProperty p; //non-unique
bool operator<(const MyItem& other) const {
return p < other.p;
}
};
假设我按时间顺序添加了 100 个对象,如果我在那个容器上 运行 qStableSort(从而按 p
排序),我是否可以保证一个给定的值p
,他们仍然按时间顺序排列?
https://en.wikipedia.org/wiki/Category:Stable_sorts
Stable sorting algorithms maintain the relative order of records with equal keys (i.e. values). That is, a sorting algorithm is stable if whenever there are two records R and S with the same key and with R appearing before S in the original list, R will appear before S in the sorted list.
因此 qStableSort
中的关键字 stable 正是指您所要求的。
但是请注意,qStableSort
是 obsoleted in Qt 5.5
Use std::stable_sort instead.
Sorts the items in range [begin, end) in ascending order using a stable sorting algorithm.
If neither of the two items is "less than" the other, the items are taken to be equal. The item that appeared before the other in the original container will still appear first after the sort. This property is often useful when sorting user-visible data.
根据 Qt 文档,您应该更喜欢使用 std::stable_sort