Results 1 to 3 of 3

Thread: std::max_element and overload operator()

  1. #1
    Join Date
    Jan 2006
    Posts
    976
    Thanks
    53
    Qt products
    Qt3
    Platforms
    Windows

    Default std::max_element and overload operator()

    Hello,
    I need to do this but it, but with the //trick it works only with max_element. Do I have to write another class Less_Than ?
    ( I added that trick because it didn't work proper when NaN is the FIRST element of vector)
    Qt Code:
    1. #include <limits>
    2. class More_Than {
    3. public:
    4. More_Than() {}
    5. bool operator() (const double& left, const double& right) {
    6. if ( _isnan(left) ) return true; //trick
    7. if (left < right)
    8. return true;
    9. return false;
    10. }
    11. };
    12. int main (int argc, char** argv) {
    13.  
    14. vector<double> vecInt(6);
    15. vecInt[0] = std::numeric_limits<double>::quiet_NaN();
    16. vecInt[1] = 9;
    17. vecInt[2] = 25;
    18. vecInt[3] = 50;
    19. vecInt[4] = 5;
    20. vecInt[5] = 33;
    21.  
    22. double max = *std::max_element( vecInt.begin(), vecInt.end(), More_Than() );
    23. double min = *std::min_element( vecInt.begin(), vecInt.end(), More_Than() );
    24. }
    To copy to clipboard, switch view to plain text mode 
    Regards

  2. #2
    Join Date
    Jan 2006
    Location
    Shanghai, China
    Posts
    52
    Thanks
    3
    Qt products
    Qt3 Qt4
    Platforms
    Unix/X11 Windows

    Default Re: std::max_element and overload operator()

    You can add a parameter to the More_Than class:
    Qt Code:
    1. class More_Than {
    2. bool flag;
    3. public:
    4. More_Than(bool f) {flag=f}
    5. bool operator() (const double& left, const double& right) {
    6. if ( _isnan(left) ) return flag; //trick
    7. if (left < right)
    8. return true;
    9. return false;
    10. }
    11. };
    To copy to clipboard, switch view to plain text mode 

    However, I suggest kick those NaN numbers out of the list at the first place before you compare them.
    1. Users don't have the manual, and if they did, they wouldn't read it.
    2. In fact, users can't read anything, and if they could, they wouldn't want to.

  3. #3
    Join Date
    Jan 2006
    Posts
    976
    Thanks
    53
    Qt products
    Qt3
    Platforms
    Windows

    Default Re: std::max_element and overload operator()

    there are many NaN to kick out, then it could be not fast....
    Regards

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Digia, Qt and their respective logos are trademarks of Digia Plc in Finland and/or other countries worldwide.