Does std::sort change the relative order of equal

2020-03-14 03:34发布

Does the standard guarantee that order of equal elements will not change (eh, forgot the term for that) by using std::sort or do I need to consider an alternative solution to achieve this goal?

标签: c++ stl
5条回答
相关推荐>>
2楼-- · 2020-03-14 03:58

No, if you want the guarantee use std::stable_sort

查看更多
smile是对你的礼貌
3楼-- · 2020-03-14 03:59

No it explicitly does not guarantee this. If you need to maintain relative ordering use stable_sort instead.

Documentation of sort which includes reference to equivalent elements

查看更多
倾城 Initia
4楼-- · 2020-03-14 04:18

std::sort is not guaranteed to be stable (the term you were trying to think of). As you'd guess, std::stable_sort is guaranteed to be stable. std::stable_sort also provides a guarantee on worst-case complexity, which std::sort does not. std::sort is typically faster on average though.

查看更多
We Are One
5楼-- · 2020-03-14 04:20

From C++ reference: here

Elements that would compare equal to each other are not guaranteed to keep their original relative order.

You might want stable_sort, but note that it's not as fast (in average)

查看更多
够拽才男人
6楼-- · 2020-03-14 04:21

The term for what you're describing is stability.

From SGI's STL docs:

Note: sort is not guaranteed to be stable.

Use stable_sort if you need this.

查看更多
登录 后发表回答