为什么 __gcd() 在 macOS mojave 中抛出错误?

Why __gcd() is throwing error in macOS mojave?

本文关键字:出错 错误 mojave macOS gcd 为什么      更新时间:2023-10-16
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>

using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);

for(int i = 0; i < n; ++i)
cin >> a[i];
int ans = a[0];
for(int i = 1; i < n; ++i)
ans = __gcd(ans, a[i]);
cout << ans << endl;
return 0;
}

它抛出以下错误:

错误:由于要求"!is_signed::值"而失败static_assert

注意:在函数模板专用化的实例化中,此处请求了"std::__1::__gcd" ans = __gcd(ans, a[i](;

我正在使用命令 g++ -std=c++17,它适用于除此程序之外的所有程序。

此代码在使用 g++ 5.4.0 的在线编译器上 code.hackerearth.com 没有错误

编辑:删除了bits/stdc ++ .h标头,仅包含所需的标头。

删除后也发生了同样的问题。

SAME 代码在联机 ide 中正常运行。一个这样的IDE的链接是在线IDE。

使用他们的 c++ 编译器和函数 __gcd a, b( 不会给出任何错误,但是当我在同一 ide 中将其更改为 gcd(a, b( 时,它确实会给出找不到此函数定义的错误。

当我在本地机器中运行相同的代码时,一切都以相反的方式发生。 __gcd(a, b( 不起作用,而 gcd(a, b( 工作。

不要使用bit/C++.h,它是一个私有标头。

使用正确的C++函数:https://en.cppreference.com/w/cpp/numeric/gcd

它们支持有符号整数。

#include <iostream>
#include <vector>
#include <numeric>
using namespace std;
int main() {
int n;
cin >> n;
vector<int> a(n);
for(int i = 0; i < n; ++i)
cin >> a[i];
int ans = a[0];
for(int i = 1; i < n; ++i)
ans = gcd(ans, a[i]);
cout << ans << endl;
return 0;
}

clang++ -std=c++17一起工作。

正如另一个答案所说,如果可能的话,使用标准std::gcd而不是非标准__gcd

也就是说,该错误意味着__gcd仅适用于无符号整数。将变量的类型从int更改为unsigned int

int gcd(int a, int b){
if (b == 0)
return a;
return gcd(b, a % b); 
}

就像在我的mac中一样,"__gcd(("也无法正常工作并显示"使用未声明的标识符",因此我必须预定义此功能。

相关文章: