Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::sort behavior with ints that are equal

Tags:

c++

sorting

std

What is the behavior of std::sort when used with ints that are equal is it going to keep them in the same order or just do some unpredictable stuff?

like image 201
DogDog Avatar asked Nov 05 '10 15:11

DogDog


2 Answers

std::sort doesn't preserve the order of the equivalent elements, std::stable_sort does. However, in case of int's you will not notice the difference unless you use some non-trivial ordering as in the following example:

struct half_less
{
    bool operator()(int a, int b) const { return (a / 2) < (b / 2); }
};

std::sort(begin, end, half_less());

Here is another example when std::stable_sort is a more suitable candidate than std::sort

like image 159
vitaut Avatar answered Oct 15 '22 17:10

vitaut


@vitaut is right. I just want to add that you would not notice if the order of equal integers is changed. This only matters if you sort values which happen to have an indentifying property. For example if you store pointers to integers and sort by the integer value.

like image 24
frast Avatar answered Oct 15 '22 16:10

frast