简体   繁体   English

C++ std::sort 自定义比较器在比较器返回 true 时无限期运行

[英]C++ std::sort custom comparator runs indefinitely when the comparator returns true

So I encountered this very weird behavior on an edge case when sorting a vector using a custom comparator.因此,在使用自定义比较器对向量进行排序时,我在边缘情况下遇到了这种非常奇怪的行为。

When running this code, it will not halt, and goes forever:运行此代码时,它不会停止,并且永远运行:

int main() {
    auto comp = [](int lhs, int rhs) {
        return true;
    };
    
    vector<int> vec{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
    sort(vec.begin(), vec.end(), comp);
    
    for (int num : vec)
        cout << num;
    
    return 0;
}

however, when I change the true to false , it works perfectly.但是,当我将true更改为false ,它可以完美运行。

auto comp = [](int lhs, int rhs) {
    return false;
};

What's weirder, when I decrease the number of 0 's to be sorted, it also works perfectly.更奇怪的是,当我减少要排序的0的数量时,它也能完美运行。 (It works with 16 or less 0 's, when I add one more 0 to make it 17, the program will not halt again. (Will g++ switch to another sorting algorithm if the length exceeds 16?) (它适用于 16 个或更少的0 ,当我再添加一个0使其成为 17 时,程序将不会再次停止。(如果长度超过 16,g++ 会切换到另一种排序算法吗?)

vector<int> vec{0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};

Why is this the case?为什么会这样? Am I missing some important concepts in C++'s sort() function?我是否遗漏了 C++ 的sort()函数中的一些重要概念?

This comparator:这个比较器:

auto comp = [](int lhs, int rhs) {
   return true;
};

violates the requirement of std::sort that the comparator must establish a strict-weak-ordering .违反std::sort的要求,即比较器必须建立严格弱排序 Note that this function returns true regardless of the order of arguments, implying that 2 elements can both be less than the other, which doesn't really make sense.请注意,无论参数的顺序如何,此函数都返回true ,这意味着 2 个元素都可以小于另一个,这实际上没有意义。 Violating this requirement of std::sort invokes undefined behavior (this is sufficient to explain the differing behavior you see with different vector sizes).违反std::sort这个要求会调用未定义的行为(这足以解释您看到的不同vector大小的不同行为)。


On the other hand, this comparator:另一方面,这个比较器:

auto comp = [](int lhs, int rhs) {
    return false;
};

is perfectly fine.完全没问题。 It basically says that no elements compare less than any other (ie they are all equivalent).它基本上是说没有元素比其他元素少(即它们都是等价的)。 This satisfies strict-weak-ordering , so std::sort will work just fine with it.这满足strict-weak-ordering ,因此std::sort可以很好地使用它。

Of course, std::sort won't do anything useful with the second comparator, since all the elements are already "sorted".当然, std::sort不会对第二个比较器做任何有用的事情,因为所有元素都已经“排序”了。 This might reorder the elements though;不过,这可能会重新排列元素; but if you use std::stable_sort then the original range is guaranteed to be unchanged.但是如果你使用std::stable_sort那么原始范围保证不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM