-
November 8th, 2010, 01:04 PM
#1
[RESOLVED] max in c++
Why can't I use e.g.:
int x = 5;
double y = 1.3;
cout<<max(x,y)<<endl;
-
November 8th, 2010, 01:23 PM
#2
-
November 8th, 2010, 01:28 PM
#3
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;
-
November 8th, 2010, 01:28 PM
#4
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;
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|