Reputation:
I have two vectors "a" and "b" of long long ints, and I wish put the difference of respective elements of "a" and "b" into a vector "c". But I don't want these differences to go below 0.
#include<bits/stdc++.h>
using namespace std;
int main(){
vector<long long int> a={360757931684,484141693549};
vector<long long int> b={186119101678,675563431537};
vector<long long int> c;
vector<long long int> d;
for (int i=0; i<2; i++){
// c.push_back(max(0,a[i]-b[i]));
c.push_back(max(0ll,a[i]-b[i]));
//I need to use "0ll" to make this work, Because the commented line above doesn't work
}
for (int i=0; i<2; i++){
if (a[i]-b[i]>0)
//Here this works fine even without "0ll"
d.push_back(a[i]-b[i]);
else
d.push_back(0);
}
return 0;
}
While using std::max
function I had to use 0ll
, but while using >
operator using only 0
was sufficient. Why?
Upvotes: 3
Views: 1226
Reputation: 1201
That's because std::max must be given two parameters of the exact same type, whereas int
and long long int
are two different types. If you write std::max(0, a[i]-b[i])
, it will not compile, because the type of a[i]-b[i]
is long long int
, and the type of 0
is int
.
Longer answer:
std::max
is a function template. The overload you are using has one template parameter T
, and two parameters const T& a
and const T& b
. When you call std::max
, you can explicitly specify the template parameter like this.
std::max<long long int>(0, a[i]-b[i])
In this case, the compiler will generate a function that receives two long long int
s, and you can actually pass anything convertible to long long int
to the function.
However, if you do not specify the template parameter T
, template argument deduction will try to deduce it for you.
Here is how it works. The first parameter is const T& a
, so the compiler tries to deduce T
based on what you passed as an argument. You pass 0
, so the compiler deduces that T
is an int
Then the compiler tries to deduce T
using the second parameter const T& b
. You passed a long long int
, so the compiler deduces that T
must be a long long int
.
The compiler then fails to instantiate the function template because it deduced conflicting types for the same template parameter.
Failing to instantiate the function template std::max
with the specified arguments, the compiler fails to find a matching function to call, that's why you are getting a compile error.
Upvotes: 3