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?
当std :: sort与相同的int一起使用时,它会保持相同的顺序还是只做一些不可预测的东西?
2 个解决方案
#1
16
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:
std :: sort不保留等效元素的顺序,std :: stable_sort确实如此。但是,如果是int,你将不会注意到差异,除非你使用一些非平凡的排序,如下例所示:
struct half_less
{
bool operator()(int a, int b) const { return (a / 2) < (b / 2); }
};
std::sort(begin, end, half_less());
#2
5
@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.
@vitaut是对的。我只想补充一点,你不会注意到是否改变了相等整数的顺序。这只有在您对具有识别属性的值进行排序时才有意义。例如,如果存储指向整数的指针并按整数值排序。
#1
16
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:
std :: sort不保留等效元素的顺序,std :: stable_sort确实如此。但是,如果是int,你将不会注意到差异,除非你使用一些非平凡的排序,如下例所示:
struct half_less
{
bool operator()(int a, int b) const { return (a / 2) < (b / 2); }
};
std::sort(begin, end, half_less());
#2
5
@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.
@vitaut是对的。我只想补充一点,你不会注意到是否改变了相等整数的顺序。这只有在您对具有识别属性的值进行排序时才有意义。例如,如果存储指向整数的指针并按整数值排序。