【问题标题】:here I'm using in-built stl max function, but it's not working [duplicate]在这里我使用内置的 stl max 函数,但它不起作用[重复]
【发布时间】:2021-12-05 03:00:20
【问题描述】:
int maxDepth(string s) {
    stack<char>st;
    int ans=0;
    for(char ch:s){
        if(ch=='('){
            st.push('(');
            ans=max(ans,st.size());
        } else if(ch==')') st.pop();
    }
    return ans;
}

它显示

Line 9: Char 21: error: no matching function for call to 'max'
                ans=max(ans,st.size());
                    ^~~
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/algorithmfwd.h:370:5: note: candidate template ignored: deduced conflicting types for parameter '_Tp' ('int' vs. 'unsigned long')
    max(const _Tp&, const _Tp&);
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:3462:5: note: candidate template ignored: could not match 'initializer_list<type-parameter-0-0>' against 'int'
    max(initializer_list<_Tp> __l, _Compare __comp)
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/stl_algo.h:3456:5: note: candidate function template not viable: requires single argument '__l', but 2 arguments were provided
    max(initializer_list<_Tp> __l)
    ^
/usr/bin/../lib/gcc/x86_64-linux-gnu/9/../../../../include/c++/9/bits/algorithmfwd.h:375:5: note: candidate function template not viable: requires 3 arguments, but 2 were provided
    max(const _Tp&, const _Tp&, _Compare);
    ^
1 error generated.

【问题讨论】:

  • TL;DR std::max 要求两个参数具有相同的类型,但您有 intstd::size_t。选择一个。

标签: c++ stl


【解决方案1】:
int maxDepth(string s) {
    stack<char>st;
    //int ans=0; <<< this is signed but stack size is unsigned change it to 
    size_t ans=0;
    for(char ch:s){
        if(ch=='('){
            st.push('(');
            ans=max(ans,st.size()); //<<< you cant do max with different types
        } else if(ch==')') st.pop();
    }
    return ans;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 2021-04-02
    • 1970-01-01
    相关资源
    最近更新 更多