c++ - std::sort with equal elements gives Segmentation fault -


i have container storing pointers. trying sort these pointers in non-increasing order based on data member in corresponding objects pointed pointers. in case, possible many objects have same value data member.

the following short code illustrate problem. call sort function giving segmentation fault. weird thing is, if have 16 elements in container pointing objects same value double, sort seems work. if have 17 elements pointing objects same value, gives seg fault.

can please explain why happens?

#include <iostream> #include <algorithm> #include <deque>  //some class class { 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 pointers container     for(int = 1; i<=17; i++) {         adeque.push_back(new a(5));     }      //this call sort gives segmentation fault     std::sort(adeque.begin(), adeque.end(), cmp_a_obj);      for(std::deque<a*>::iterator = adeque.begin(); i!= adeque.end(); i++) {         std::cout << "|" << (*i)->a;     }     std::cout << std::endl; } 

your comparison must implement strict weak ordering. less or equal not satisfy this. should equivalent "less than" or "greater than" implemented in operators < , > for, say, integers.

equality of elements determined applying ordering twice:

(!cmp(a,b)) && (!cmp(b,a)); // if false, == b 

Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -