[英]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.就我而言,许多对象可能对该数据成员具有相同的值。
The following is a short code to illustrate the problem.下面是一个简短的代码来说明问题。 The call to the sort function is giving a Segmentation fault.对 sort 函数的调用给出了 Segmentation 错误。 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.奇怪的是,如果容器中有 16 个元素指向具有相同双精度值的对象,则排序似乎有效。 But if I have 17 elements pointing to objects with same value, it gives a seg fault.但是,如果我有 17 个元素指向具有相同值的对象,则会出现段错误。
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.