Home > Mobile >  Why am i getting error "call of overloaded 'abs(long long unsigned int)' is ambiguous
Why am i getting error "call of overloaded 'abs(long long unsigned int)' is ambiguous

Time:12-06

so i tried to compile the following code:

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<int> nums;
    while(n--){
        int temp;
        cin>>temp;
        nums.push_back(temp);
    }
    long long sum=0;
    for(int i:nums){
        sum =i;
    }
    int index;
    long long temp_sum=0,avgdiff=0,min_avgdiff=LLONG_MAX;
    for(int i=0;i<nums.size();i  ){
        temp_sum =nums[i];
        if(i!=nums.size()-1) avgdiff=abs((temp_sum/(i 1))-((sum-temp_sum)/(nums.size()-i-1)));
        else avgdiff=temp_sum/(i 1);    
        if(min_avgdiff>avgdiff){
            min_avgdiff=avgdiff;
            index=i;
        }
    }
    cout<<index;

    return 0;
}

after which i got an error like this at line 22(the longest line in the code): "error: call of overloaded 'abs(long long unsigned int)' is ambiguous".

but when i modified my code as shown below:

#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<int> nums;
    while(n--){
        int temp;
        cin>>temp;
        nums.push_back(temp);
    }
    long long sum=0;
    for(int i:nums){
        sum =i;
    }
    int index;
    long long temp_sum=0,avgdiff=0,min_avgdiff=LLONG_MAX;
    for(int i=0;i<nums.size();i  ){
        temp_sum =nums[i];
        long long avg1=temp_sum/(i 1),avg2=0;
        if(i!=nums.size()-1){
            avg2=(sum-temp_sum)/(nums.size()-i-1);
        }
        avgdiff=abs(avg1-avg2);
        if(min_avgdiff>avgdiff){
            min_avgdiff=avgdiff;
            index=i;
        }
    }
    cout<<index;

    return 0;
}

i didn't get any error!! can anyone explain me why?

CodePudding user response:

nums.size() is an unsigned value (size_t), which means the whole expression (temp_sum/(i 1))-((sum-temp_sum)/(nums.size()-i-1)) is unsigned. There's no overload of the function abs taking an unsigned value (specifically in your case, a long long unsigned int), so it doesn't know which version of the function to call.

Your second piece of code works because you assign this unsigned value into a variable with a signed type, and then call abs on that signed value.

  •  Tags:  
  • c
  • Related