std::sort 会改变相等元素的相对顺序吗?
标准是否通过使用 std::sort 保证相等元素的顺序不会改变(呃,忘记了这个术语),或者我是否需要考虑替代解决方案来实现此目标?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
std::sort
不保证稳定(您试图想到的术语)。正如您所猜测的,std::stable_sort
保证是稳定的。std::stable_sort
还提供了对最坏情况复杂性的保证,而std::sort
则没有。不过,std::sort
平均而言通常更快。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, whichstd::sort
does not.std::sort
is typically faster on average though.来自 C++ 参考:此处
您可能需要 stable_sort,但请注意,它的速度没有那么快(平均而言)
From C++ reference: here
You might want stable_sort, but note that it's not as fast (in average)
不,如果你想保证使用 std::stable_sort
No, if you want the guarantee use std::stable_sort
不,它明确不保证这一点。如果需要保持相对顺序,请使用 stable_sort 代替。
包含对等效元素的引用的排序文档
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
您所描述的术语是稳定性。
来自 SGI 的 STL 文档:
如果需要,请使用
stable_sort
。The term for what you're describing is stability.
From SGI's STL docs:
Use
stable_sort
if you need this.