加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 10:40:52 所属栏目:百科 来源:网络整理
导读:我已经设法找到一个可重现的例子,说明我用std :: sort看到的奇怪行为 我试图对一对对列表进行排序,它应该在第二个元素上排序.第二个要素的清单是[1 1 1 1 3 1 1 1 1 1 1 3 2 1 1 5 2 1 7 1]. 以下是我的代码: std::vectorpairint,double pairs;for (int i =
我已经设法找到一个可重现的例子,说明我用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,3));
for (int i = 0; i < 6; i++) {
    pairs.push_back(pair<int,3));
pairs.push_back(pair<int,2));
pairs.push_back(pair<int,1));
pairs.push_back(pair<int,5));
pairs.push_back(pair<int,7));
pairs.push_back(pair<int,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);

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

整个输出可以找到here,但有一些奇怪的行(即链接页面中的第46行),其中显示:

sorting (0,1)

但是0没有出现在输入列表中.这是为什么?

解决方法

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

关于严格的弱排序,它还包括以下属性

(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)及物性

对于运算符&lt ;: If x< y是真的,y< z为真,则x < z是真的.
???对于谓词op():如果op(x,y)为真且op(y,z)为真,则op(x,z)
是真的.

(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

For all algorithms that take Compare,there is a version that uses operator< instead. That is,1comp(*i,*j) != false1 defaults to *i < *j != false. For algorithms other than those described in 25.4.3 to work correctly,comp has to induce a strict weak ordering on the values.

阅读更多关于strict weak ordering的信息

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读