CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Oct 2009
    Location
    NY, USA
    Posts
    191

    [RESOLVED] max in c++

    Why can't I use e.g.:
    int x = 5;
    double y = 1.3;

    cout<<max(x,y)<<endl;

  2. #2
    Join Date
    Sep 2004
    Location
    Holland (land of the dope)
    Posts
    4,123

    Re: max in c++

    Why can't you use it ?

  3. #3
    Lindley is offline Elite Member Power Poster
    Join Date
    Oct 2007
    Location
    Seattle, WA
    Posts
    10,895

    Re: max in c++

    There are actually several possible reasons that might break.

    First, under Visual Studio, Microsoft has for some reason defined max() and min() as macros even though there are perfectly good STL implementations of those names in <algorithm>. You'll need to get rid of the macros to avoid compile errors; add
    #define NOMINMAX
    to the top of your file (above any includes).

    Second, the algorithms std::min and std::max are templated. They expect to take the same type in each argument; if you're trying to call std::max(int,double), then the compiler can't always figure out whether you really want std::max<int>(int,int) or std::max<double>(double,double). One workaround here is to explicitly specify which you want:
    Code:
    cout<<max<double>(x,y)<<endl;

  4. #4
    Join Date
    Jan 2006
    Location
    Singapore
    Posts
    6,765

    Re: max in c++

    The max function template requires the arguments to have the same type (more or less). You can coerce it to do what you want, e.g.,
    Code:
    cout << max(static_cast<double>(x), y) << endl;
    C + C++ Compiler: MinGW port of GCC
    Build + Version Control System: SCons + Bazaar

    Look up a C/C++ Reference and learn How To Ask Questions The Smart Way
    Kindly rate my posts if you found them useful

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured