[英]How to fix "error: call to 'abs' is ambiguous"
我正在从 HackerRank 运行一个关于指针的简单 C++ 程序,它在网站上运行良好。 但是,当我在 MacOS 上运行它时, error: call to 'abs' is ambiguous
,我不确定到底什么是不明确的。
我看过类似问题的其他答案,但错误消息往往是Ambiguous overload call to abs(double)
,这不是我遇到的问题,因为我没有使用任何双打。 我也试过包含头文件cmath
和math.h
,但问题仍然存在。
#include <stdio.h>
#include <cmath>
void update(int *a,int *b) {
int num1 = *a;
int num2 = *b;
*a = num1 + num2;
*b = abs(num1 - num2);
}
int main() {
int a, b;
int *pa = &a, *pb = &b;
scanf("%d %d", &a, &b);
update(pa, pb);
printf("%d\n%d", a, b);
return 0;
}
我的问题出现在第 8 行。
完整的错误信息是:
$ clang++ test.cpp
test.cpp:8:10: error: call to 'abs' is ambiguous
*b = abs(num1 - num2);
^~~
.../include/c++/v1/math.h:769:1: note: candidate function
abs(float __lcpp_x) _NOEXCEPT {return ::fabsf(__lcpp_x);}
^
.../include/c++/v1/math.h:769:1: note: candidate function
abs(double __lcpp_x) _NOEXCEPT {return ::fabs(__lcpp_x);}
^
.../include/c++/v1/math.h:769:1: note: candidate function
abs(long double __lcpp_x) _NOEXCEPT {return ::fabsl(__lcpp_x);}
^
1 error generated.
<cmath>
的三个abs
重载是abs(float)
、 abs(double)
和abs(long double)
; 这是模棱两可的,因为您有一个int
参数,而编译器不知道要转换为哪种浮点类型。
abs(int)
在<cstdlib>
定义,所以#include <cstdlib>
将解决您的问题。
如果您使用的是 Xcode,则可以在问题导航器 (⌘5) 中获取有关错误的更多详细信息,然后单击问题旁边的三角形。
对我来说, #include <cstdlib>
没有解决这个问题,也许是因为我不需要包含任何东西来使用abs
。 因此,如果它可以帮助其他人,通过显式转换,它对我来说效果很好,就像在下一个代码中一样:
*b = abs(int(num1 - num2));
如果您使用 C 编译器,您应该包括
#include <stdlib.h>
并使用不带 std:: 的 abs。 如果您使用 C++ 编译器,那么您应该将 abs 更改为 std::abs。
希望能帮助到你:)
在模板化代码中,很容易忽略std::abs
没有为无符号类型定义。 例如,如果为无符号类型实例化以下方法,编译器可能会抱怨std::abs
未定义:
template<typename T>
bool areClose(const T& left, const T& right) {
// This should better be implemented separately for integral types,
// which would also solve the problem of std::abs() being undefined:
return (std::abs(left - right) < 1e-7);
}
int main() {
uint32_t vLeft = 17;
uint32_t vRight = 18;
std::cout << "are close: " << areClose(vLeft, vRight) << std::endl;
}
上面代码中对areClose()
更好定义,巧合的是也解决了std::abs()
未定义的问题,可能如下所示:
template<typename T>
bool areClose(const T& left, const T& right) {
if constexpr (std::is_integral<T>::value) {
return (left == right);
} else {
return (std::abs(left - right) > 1e-7);
}
}
我使用#include <bits/stdc++.h>
作为唯一的包含语句,它对我有用。 我的代码:
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
vector<int> findDuplicates(vector<int>& nums) {
int n = nums.size();
if(n == 0 || n == 1)
return {};
vector<int> ans;
for(int i = 0; i < n; i++)
{
if(nums[abs(nums[i])-1] < 0)
ans.push_back(abs(nums[i]));
else
nums[abs(nums[i])-1] = -1 * nums[abs(nums[i])-1];
}
return ans;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.