Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting the error with max function when I use long long int and int as arguments

Tags:

c++

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]);"
like image 412
shivareddy57 Avatar asked Sep 05 '25 20:09

shivareddy57


1 Answers

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

like image 126
CuriouslyRecurringThoughts Avatar answered Sep 08 '25 13:09

CuriouslyRecurringThoughts