[英]Why am I getting errors about int not matching unsigned long?
[英]Why am I getting the error with max function when I use long long int and int as arguments
我是 C++ 的新手,在使用max
function 时遇到了这个意外错误,我通过 arguments 类型为 long long 和 int
当我将(int,int)
作为 arguments 或(long long,long long)
传递时,它可以正常工作,但不能与(long long,int)
一起使用
ll painter(int board[],int n,int k)
{
ll s = 0,total_min;
ll ans;
for(ll i = 0;i < n;i++)
{ total_min += board[i];
s = max(s,board[i]);
}
这是显示的错误
prog.cpp:39:25: error: no matching function for call to 'max(int&, long long int&)
s =max(s,board[i]);"
std::max
的签名为:
template< class T >
constexpr const T& max( const T& a, const T& b );
因此, max
期望两个参数都属于同一类型,如果它们不是同一类型,则您需要明确设置模板参数:
std::max<long long int>(s, board[i])
或者,您需要确保两个参数的类型相同。
因为std::max
是一个函数模板,其签名例如是
template< class T >
const T& max( const T& a, const T& b );
完整列表位于: https : //en.cppreference.com/w/cpp/algorithm/max
现在,在实例化模板时,您提供了两种不同的类型,但是模板只需要一种。 您必须像下面的示例一样显式指定模板参数:
#include <algorithm>
int main(){
int a{5};
long long int b{55};
return std::max<long long int>(a, b);
}
如注释中所述(用户John),您还可以强制转换这两者之一,例如,可以将int
为long long
std :: max()接受相同类型的参数。 如果要比较两个不同的变量,则必须将一个变量转换为另一个变量。 在这种情况下,我建议将int转换为long long int,这样就不会丢失任何内容。
你必须使用这个: max(s, board[i]); 它会起作用的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.