Search code examples
c++functionstackmax

Why max() function in C++ giving error "no matching function for call to max"? Same code works if I do it explicitly with conditional statement


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;
    }

Solution

  • 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

     template<typename _Tp>
        _GLIBCXX14_CONSTEXPR
        inline const _Tp&
        max(const _Tp& __a, const _Tp& __b)
        {
          // concept requirements
          __glibcxx_function_requires(_LessThanComparableConcept<_Tp>)
          //return  __a < __b ? __b : __a;
          if (__a < __b)
        return __b;
          return __a;
        }
    

    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 an int and other is a size_t which is an unsigned int then you will have an error.

    Here's what you can do when using std::max:

    1. Cast so the parameters match:

      maxDepth = max(static_cast<size_t>(maxDepth), stac.size()); 
      
    2. Declare the type, which is also more readable:

      maxDepth = max<size_t>(maxDepth, stac.size())
      

    Regarding your own program, I advise that you change the type of maxDepth to size_t.

    Also, for readability, change the function name so it does not have the same name as the variable.