4

I'am new to C++ just had this unexpected error with using max function, where I pass arguments of type long long and int

When i pass (int,int) as arguments or (long long,long long) it works fine but not with (long long,int)

ll painter(int board[],int n,int k)
{

 ll  s = 0,total_min;
 ll ans;

 for(ll i = 0;i < n;i++)
   { total_min += board[i];
       s = max(s,board[i]);

}

This is the error showing

prog.cpp:39:25: error: no matching function for call to 'max(int&, long long int&)
        s =max(s,board[i]);"
3
  • 3
    Because the template function max expects the two arguments to be of the same type, and because the usual arithmetic conversion rules don't apply when calling a template function. Just add a cast, and don't use typedefs like ll.
    – john
    Jul 27, 2019 at 11:16
  • Aside: You could instead write this as ll s = *std::max_element(board, board+n); ll total_min = std::accumulate(board, board+n, 0); (assuming n is never 0). Another aside: you don't initialise total_min, so your program has undefined behaviour
    – Caleth
    Aug 17, 2022 at 9:10
  • This feature is confusing to novices because the normal relational operators (>, < etc.) perform conversions but the closely related (in meaning) std::max() does not.
    – Persixty
    Aug 17, 2022 at 9:42

3 Answers 3

4

Because std::max is a function template whose signature is, for example,

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

complete list at: https://en.cppreference.com/w/cpp/algorithm/max

Now, when instantiating the template you give two different types but the templates only wants one. You have to explicitly specify the template argument, like in this example:

#include <algorithm>

int main(){
    int a{5};
    long long int b{55};
    return std::max<long long int>(a, b);
}   

As noted in the comments (user John), you can also cast one of the two, for example you can cast the int to long long

2

The signature of std::max is:

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

So max expects both arguments to be of the same type, if they are not fo the same type then you explicitly need set the template argument:

std::max<long long int>(s, board[i])

Or you need to ensure that both arguments are of the same type.

0

std::max() accepts parameters that are of the same type. If you want to compare two variables that are not of the same you will have to cast one into another. In this case i suggest casting int into long long int so you don't lose anything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.