【问题标题】:std::max giving error C2064: term does not evaluate to a function taking 2 argumentsstd::max 给出错误 C2064:术语不计算为采用 2 个参数的函数
【发布时间】:2021-04-14 12:20:41
【问题描述】:

我对 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], cuts),   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

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

【问题讨论】:

    标签: visual-c++ stl c++17


    【解决方案1】:

    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&lt;T&gt; 的重载。 std::initializer_list 可以从花括号列表中自动创建:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-02-19
      • 2011-09-27
      • 1970-01-01
      • 2018-10-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多