std::sort with equal elements gives Segmentation fault

烂漫一生 提交于 2019-12-19 03:31:11

问题


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. 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;
}

回答1:


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


来源:https://stackoverflow.com/questions/16535882/stdsort-with-equal-elements-gives-segmentation-fault

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!