std :: sort与相等的元素给出细分错误 [英] std::sort with equal elements gives Segmentation fault
问题描述
我有一个存储指针的容器.我试图基于指针所指向的相应对象中的数据成员,以不递增的顺序对这些指针进行排序.在我的情况下,该数据成员可能有许多对象具有相同的值.
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与相等的元素给出细分错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!