News for hackers. Stuff that matters.
Re:Popular Myths about C++, Part 3 by pavanky on Monday December 22, 2014 @09:30PM (#8786534)
The C greater function is unnecessarily long

  int greater(const void* p, const void* q)
  {
     return *(double *)p - *(double *)q;
  }
would work just as well.

EDIT: DON'T USE THIS, WONT ALWAYS WORK

Re:Popular Myths about C++, Part 3 by kbwt on Monday December 22, 2014 @09:35PM (#8786545)
That is technically undefined behavior, because the result of the double subtraction could very well be a number that is not representable within the range of a signed int.
Re:Popular Myths about C++, Part 3 by _RPM on Monday December 22, 2014 @10:21PM (#8786632)
What is the point of defining the function with two void* arguments if the cast will just take place anyway?
Re:Popular Myths about C++, Part 3 by huu on Monday December 22, 2014 @10:29PM (#8786652)
The signature of greater is relevant because it has to conform to the interface for qsort. See the final argument of the interface here: http://www.cplusplus.com/reference/cstdlib/qsort/
Re:Popular Myths about C++, Part 3 by alayne on Monday December 22, 2014 @09:35PM (#8786547)
Don't do this. It has overflow issues.
Re:Popular Myths about C++, Part 3 by pavanky on Monday December 22, 2014 @09:38PM (#8786552)
You are right. He was really careful in picking double instead of int for this example.
Re:Popular Myths about C++, Part 3 by ridiculous_fish on Tuesday December 23, 2014 @12:15AM (#8786869)
Actually I would say it was rather careless, because it mishandles NaNs:

    vector<double> v = {0, nan(""), 1};
    sort(v.begin(), v.end(), [](double x, double y) { return x>y; });
In my test this leaves the vector unchanged, which is definitely not in decreasing order.
Re:Popular Myths about C++, Part 3 by lomnakkus on Tuesday December 23, 2014 @12:44AM (#8786943)
">" does not form a total order on doubles if you include NaN, so that's not really suprising. That is, you're providing a comparison function which is invalid, you should (at best) expect invalid results.