1
class StrangeFunctor 
{ 
  public: 
    StrangeFunctor(int (*comp)(string, string)) 
     { 
       this->comp = comp; 
     } 
     int operator()(string str1, string str2) 
     { 
       return –comp(str1, str2); 
     } 
  private: 
   int (*comp)(string, string); 
} 

I was just curious as what the above code actually did. Assuming the functor was properly initialized and given to a sorting function for comparison purpose, my hunch is that it reverses the order of the passed argument, but I'm not sure if that is correct and why the would be correct.

2
  • What kind of sorting function? Certainly not std::sort. It would indeed work the way you describe for the sorting function that expects the comparison to return a negative value for less-than, zero for equals and positive for greater-than (like qsort, but you won't be able to pass a function object to qsort). Commented Apr 16, 2014 at 1:03
  • @IgorTandetnik Yes, but with one exception: if comp returns INT_MIN, then - will cause overflow (assuming normal two's complement implementation of int).
    – svick
    Commented Apr 16, 2014 at 1:26

1 Answer 1

1

This functor takes in a function pointer and then flips the sign on that method's return value.

return –comp(str1, str2); 

If used with sorting like you said, it would invert the order of what was being sorted, given by the original function pointer.

0

Not the answer you're looking for? Browse other questions tagged or ask your own question.