Std :: sort with equal elements gives a segmentation error

I have a container storage pointer. I am trying to sort these pointers in a consistent manner based on the data element in the corresponding objects that the pointers point to. In my case, it is possible that many objects have the same value for this data item.

Below is a short code illustrating the problem. Calling the sort function gives a segmentation error. The strangest thing about this is, if I have 16 elements in the container pointing to objects with the same value for the double, it looks like this view works. But if I have 17 elements pointing to objects with the same value, this gives a seg error.

Can someone explain why this is happening?

#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; } 
+4
source share
1 answer

In your comparison, a strict weak order should be implemented. Less or equal, it does not satisfy. It should be equivalent to "less" or "more", as implemented in the < and > operators for, say, integers.

Equality of elements is determined by applying this order twice:

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

Source: https://habr.com/ru/post/1480634/


All Articles