为什么Max()在C+&#x2B中函数给出错误的“无匹配函数,可以呼叫最大匹配功能”?如果我在条件语句中明确执行同样的代码
最大的两个参数均为 int 类型,那么为什么我会遇到此错误?
代码是在字符串
中找到最大的降亚深度。
int maxDepth(string s) {
stack<char> stac;
int maxDepth = 0;
for(auto &elem: s) {
if(elem == '(')
stac.push(elem);
else if(elem == ')')
{
// maxDepth = max(maxDepth, stac.size()); // this doesn't work
if(stac.size() > maxDepth) // this works, why?
maxDepth = stac.size();
stac.pop();
}
}
return maxDepth;
}
Both parameters of max are of type int, then why am I getting this error?
Code is to find maximum depth of paranthesis in a string
int maxDepth(string s) {
stack<char> stac;
int maxDepth = 0;
for(auto &elem: s) {
if(elem == '(')
stac.push(elem);
else if(elem == ')')
{
// maxDepth = max(maxDepth, stac.size()); // this doesn't work
if(stac.size() > maxDepth) // this works, why?
maxDepth = stac.size();
stac.pop();
}
}
return maxDepth;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您的编译器拒绝您对
std :: Max
函数拒绝调用的原因是因为它无法推断出所需的类型。的典型实现
以下是
std :: max
_tp
/language/template_argument_deduction“ rel =“ nofollow noreferrer”>模板类型扣除工作是评估每个模板参数的类型,然后比较它们是否匹配。由于您的一个参数之一是int
,而另一个是size_t
,它是一个无符号的int,因此您将有错误。这是使用
std :: Max
:施放时可以做的事情,
声明类型,这也更可读:
关于您自己的程序,我建议您将
maxDepth
的类型更改为size> size_t
。另外,对于可读性,请更改功能名称,以使其具有与变量相同的名称。
The reason why your compiler reject your call to the
std::max
function is because it cannot deduce the type it needs.Below is a typical implementation of
std::max
Both parameters receive
_Tp
but the way that template type deduction works is it evaluates the type for each of the template parameters and then compares if they match. Since one of your parameters is anint
and other is asize_t
which is an unsigned int then you will have an error.Here's what you can do when using
std::max
:Cast so the parameters match:
Declare the type, which is also more readable:
Regarding your own program, I advise that you change the type of
maxDepth
tosize_t
.Also, for readability, change the function name so it does not have the same name as the variable.