std::sort 给出非常奇怪的结果

2024-03-30

我设法找到了我所看到的奇怪行为的可重现示例std::sort

我正在尝试对一个成对的列表进行排序,它应该在第二个元素上排序。第二个元素的列表是[1 1 1 1 3 1 1 1 1 1 1 3 2 1 1 5 2 1 7 1].

下面是我的代码:

std::vector<pair<int, double> > pairs;
for (int i = 0; i < 4; i++) {
    pairs.push_back(pair<int, double>(1, 1));
}
pairs.push_back(pair<int, double>(1, 3));
for (int i = 0; i < 6; i++) {
    pairs.push_back(pair<int, double>(1, 1));
}
pairs.push_back(pair<int, double>(1, 3));
pairs.push_back(pair<int, double>(1, 2));
pairs.push_back(pair<int, double>(1, 1));
pairs.push_back(pair<int, double>(1, 1));
pairs.push_back(pair<int, double>(1, 5));
pairs.push_back(pair<int, double>(1, 2));
pairs.push_back(pair<int, double>(1, 1));
pairs.push_back(pair<int, double>(1, 7));
pairs.push_back(pair<int, double>(1, 1));

排序函数为:

template<typename T>
struct descending_sort {
    bool operator()(pair<T, double> const & a, pair<T, double> const & b) const {
        cout << "sorting (" << a.second << " , " << b.second << ")" << std::endl;
        return a.second >= b.second;
    }
};

descending_sort < int > d = descending_sort<int>();
std::sort(pairs.begin(), pairs.end(), d);

这会产生正确的结果,但是当我仔细检查每个步骤的排序函数的输出(我打印到控制台的内容)时,我得到了一些非常有趣的输出。

可以找到整个输出here http://pastebin.com/0WXg5s6f但有一些奇怪的行(即链接页面中的第 46 行)内容如下:

sorting (0 , 1)

但0并没有出现在输入列表中。为什么会在这里?


您的代码会导致未定义的行为,因为std::sort()需要严格的弱排序,这< or >提供,但是>=不提供,因为它违反了反对称的要求.

关于strict weak ordering,它还包括以下属性

(1) 反对称

That for operator <: If x < y is true, then y < x is false.
That for a predicate op(): If op(x,y) is true, then op(y,x) is false.

(2) 及物的

对于运算符

(3) 不自反的

That for operator <: x < x is always false.
That for a predicate op(): op(x,x) is always false.

(4) 等价传递性,大致意思是:如果a等价于b,b等价于c,则a等价于c。

§ 25.4.4

对于所有采用 Compare 的算法,都有一个使用运算符 为了使 25.4.3 中描述的算法以外的算法正常工作,comp 必须对值进行严格的弱排序。

阅读更多有关严格弱序 http://www.sgi.com/tech/stl/StrictWeakOrdering.html

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

std::sort 给出非常奇怪的结果 的相关文章

随机推荐