微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

std::max 给出错误 C2064:术语不计算为采用 2 个参数的函数

如何解决std::max 给出错误 C2064:术语不计算为采用 2 个参数的函数

我对 C++ 相当陌生。我正在练习一些 ds,algo。这段代码对我来说看起来不错,但是我收到了一些关于函数不接受 2 个参数的错误。虽然我在 stackoverflow 中遇到了一些错误,但没有一个案例符合我的问题。

#include <iostream>
#include <algorithm>


int ropecutting(int n,int *cuts){
    if (n == 0)
        return 0;
    if (n < 0)
        return -1;
    
    int res = std::max(ropecutting(n-cuts[0],cuts),ropecutting(n-cuts[1],ropecutting(n-cuts[2],cuts));
    if(res == -1) return -1;
    return res+1;
}
int main(){
    int n,cuts[3];
    std::cin >> n;
    for(int i = 0; i < 3; i ++)
        std::cin >> cuts[i];

    std::cout << ropecutting(n,cuts);
}

我得到的错误是,

main.cpp
G:\software_installation\Visual Studio Community 2017\VC\Tools\MSVC\14.16.27023\include\xlocale(319): warning C4530: C++ exception handler used,but unwind semantics are not enabled. Specify /EHsc
G:\software_installation\Visual Studio Community 2017\VC\Tools\MSVC\14.16.27023\include\algorithm(5368): error C2064: term does not evaluate to a function taking 2 arguments
G:\software_installation\Visual Studio Community 2017\VC\Tools\MSVC\14.16.27023\include\algorithm(5367): note: see reference to function template instantiation 'const _Ty &std::max<int,int>(const _Ty &,const _Ty &,_Pr) noexcept(<expr>)' being compiled
        with
        [
            _Ty=int,_Pr=int
        ]
G:\software_installation\Visual Studio Community 2017\VC\Tools\MSVC\14.16.27023\include\algorithm(5368): error C2056: illegal expression

希望有人能指出我正确的方向。谢谢。

解决方法

the overloads of std::max中,唯一可以用三个参数调用的是

template < class T,class Compare >
constexpr const T& max( const T& a,const T& b,Compare comp );

因此,由于它接收三个 int 值,该函数试图使用第三个值作为函子来比较其他两个值,这当然不起作用。

获得最多三个数字的最简单方法可能是使用带 std::initializer_list<T> 的重载。并且 std::initializer_list 可以从花括号列表中自动创建:

int res = std::max({ropecutting(n-cuts[0],cuts),ropecutting(n-cuts[1],ropecutting(n-cuts[2],cuts)});

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。