std :: sort与相等的元素给出细分错误

编程入门 行业动态 更新时间:2024-10-11 23:16:49
本文介绍了std :: sort与相等的元素给出细分错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个存储指针的容器.我试图基于指针所指向的相应对象中的数据成员,以不递增的顺序对这些指针进行排序.在我的情况下,该数据成员可能有许多对象具有相同的值.

I have a container storing pointers. I am trying to sort these pointers in non-increasing order based on a data member in the corresponding objects pointed by the pointers. In my case, it is possible that many objects have the same value for that data member.

以下是说明该问题的简短代码.对sort函数的调用给出了细分错误.奇怪的是,如果容器中有16个元素指向具有相同double值的对象,则排序似乎有效.但是,如果我有17个元素指向具有相同值的对象,则会出现段错误.

The following is a short code to illustrate the problem. The call to the sort function is giving a Segmentation fault. The weird thing about this is, if I have 16 elements in the container pointing to objects with same value for the double, the sort seems to work. But if I have 17 elements pointing to objects with same value, it gives a seg fault.

任何人都可以解释为什么会发生这种情况吗?

Can anyone please explain why this happens?

#include <iostream> #include <algorithm> #include <deque> //some class class A { public: double a; A(double aval); }; A::A(double aval) : a(aval) {} //compare class struct cmp_A : std::greater_equal<A*> { bool operator() (const A* x, const A* y) const; } cmp_A_obj; //greater_equal comparison bool cmp_A::operator() (const A* x, const A* y) const { return (x->a >= y->a); } int main() { std::deque<A*> Adeque; //insert 17 A pointers into the container for(int i = 1; i<=17; i++) { Adeque.push_back(new A(5)); } //This call to sort gives a Segmentation fault std::sort(Adeque.begin(), Adeque.end(), cmp_A_obj); for(std::deque<A*>::iterator i = Adeque.begin(); i!= Adeque.end(); i++) { std::cout << "|" << (*i)->a; } std::cout << std::endl; }

推荐答案

您的比较必须实现严格弱排序.小于或等于不满足此要求.对于整数,它应等于在运算符<和>中实现的小于"或大于".

Your comparison must implement a strict weak ordering. Less than or equal does not satisfy this. It should be equivalent to "less than" or "greater than" as implemented in operators < and > for, say, integers.

元素的相等性是通过两次应用此顺序确定的:

Equality of elements is determined by applying this ordering twice:

(!cmp(a,b)) && (!cmp(b,a)); // if this is false, a == b

更多推荐

std :: sort与相等的元素给出细分错误

本文发布于:2023-11-30 06:05:53,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1648969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:元素   错误   std   sort

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!