我正在运行来自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("%dn%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));
在模板化代码中,可能很容易忽略未为无符号类型定义std::abs
。例如,如果为无符号类型实例化了以下方法,编译器可能会理所当然地抱怨std::abs
未定义:
template<typename T>
bool areClose(const T& left, const T& right) {
// This is bad because for unsigned T, std::abs is undefined
// and for integral T, we compare with a float instead of
// comparing for equality:
return (std::abs(left - right) < 1e-7);
}
int main() {
uint32_t vLeft = 17;
uint32_t vRight = 18;
std::cout << "Are the values close? " << areClose(vLeft, vRight) << std::endl;
}
在上面的代码中对areClose()
进行更好的定义,巧合地也可以解决std::abs()
未定义的问题,如下所示:
template<typename T>
bool areClose(const T& left, const T& right) {
// This is better: compare all integral values for equality:
if constexpr (std::is_integral<T>::value) {
return (left == right);
} else {
return (std::abs(left - right) < 1e-7);
}
}
如果你使用C编译器,你应该包括
#include <stdlib.h>
并使用不含 std::的 abs。如果你使用C++编译器,那么你应该将abs更改为std::abs。
希望有帮助:(
我使用 #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;
}
};