tags:

views:

135

answers:

5

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?

+2  A: 

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

Naveen
+2  A: 

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

JaredPar
+2  A: 

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.

tgamblin
+2  A: 

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)

Matthieu M.
Right, better add the 'average' keyword to avoid confusion.
Matthieu M.
Looks good to me.
Jerry Coffin
The comment which pointed it out has probably been removed, thus letting my own pending, that I cannot really removed since it would let yours... oh well :)
Matthieu M.
+13  A: 

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.

Jerry Coffin
Note that std::sort is faster in the average case, though.
tgamblin
+! thanks... used stable sort
vehomzzz
@Jerry add this answer to this wiki (so appropriate): http://stackoverflow.com/questions/1596139/hidden-features-and-dark-corners-of-stl
vehomzzz
I expanded on it a bit, but hopefully not to the point that it gets horribly boring...
Jerry Coffin