开发者

std::sort behavior with ints that are equal

开发者 https://www.devze.com 2023-01-23 21:52 出处:网络
What is the behavior of std::sort when used with ints tha开发者_运维知识库t are equal is it going to keep them in the same order or just do some unpredictable stuff?std::sort doesn\'t preserve the ord

What is the behavior of std::sort when used with ints tha开发者_运维知识库t are equal is it going to keep them in the same order or just do some unpredictable stuff?


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


@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.

0

精彩评论

暂无评论...
验证码 换一张
取 消