简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM