std::min and std::max 出错解决方案

C++的std::min and std::max 如:

 float_t f(float_t x) const { return std::max((float_t)0.0, x); }

但是使用时如下代码:

#include "windows.h"
#include <algorithm>
void foo() {
   int i = 5;
   int j = 7;
   int x = std::max(i,j);
}

在VS中编译可能会出现以下错误:

1>test.cpp(7) : error C2589: '(' : illegal token on right side of '::'

1>test.cpp(7) : error C2143: syntax error : missing ';' before '::'

这是因为windows.h中也定义了max和min宏,当你包含了windows.h时,该程序就不能通过编译。


解决方案:
1. windows.h使用另外一个名字,只适用于windows系统。

int x = _cpp_max(i,j);
int y = _cpp_min(i,j);

该方法在系统库上改动,不推荐。
2. 不使用系统库中的std::max()std::min()函数,用其他代替如:

int x = i > j ? i : j; // max(i,j)
int y = i < j ? i : j; // min(i,j)

简单地重新实现这些函数,如果代码量大,可自己重新写一个不同名称的函数。
3. 添加命名空间using namespace std;或如下:

using std::min;
using std::max;
int x = max(i,j);
int y = min(i,j);

该方法实验不行,不知是不是我理解错了,欢迎讨论。
4. 使用 std::min<int> and std::max<int>

int x = std::max<int>(i,j);
int y = std::min<int>(i,j);

该方法需要事先知道输入数据类型,但对于i和j类型不同时会出现问题,如:

int i = 5;
unsigned int j = 7;
int x = (std::max)(i,j);
int y = (std::min)(i,j);

会出现以下错误:

1>test.cpp(7) : error C2780: 'const _Ty &std::max(const _Ty &,const _Ty &,_Pr)' :
expects 3 arguments - 2 provided
1>        c:program filesmicrosoft visual studio 8vcincludexutility(3190) :
see declaration of 'std::max'
1>test.cpp(7) : error C2782: 'const _Ty &std::max(const _Ty &,const _Ty &)' :
template parameter '_Ty' is ambiguous
1>        c:program filesmicrosoft visual studio 8vcincludexutility(3182) :
see declaration of 'std::max'
1>        could be 'unsigned int'
1>        or 'int'

总结:推荐方法2,自己实现一个相同功能的函数。

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值