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

2022-01-23 00:00:00 gcc macos g++ c++ clang++
#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::value' 导致 static_assert 失败

error: static_assert failed due to requirement '!is_signed::value'

注意:在此处请求的函数模板特化 'std::__1::__gcd' 的实例化ans = __gcd(ans, a[i]);

note: in instantiation of function template specialization 'std::__1::__gcd' requested here ans = __gcd(ans, a[i]);

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

I am using command g++ -std=c++17 which worked for every program except this one.

此代码在使用 g++ 5.4.0 的 code.hackerearth.com 在线编译器上正常工作

This code is working without error on code.hackerearth.com online compiler which uses g++ 5.4.0

删除 bits/stdc++.h 标头并仅包含必需的标头.

Removed bits/stdc++.h header and included required headers only.

删除后也出现同样的问题.

After removing also the same problem is happening.

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

The SAME code is running properly in online ide. Link of one such ide is ONLINE IDE

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

Using their c++ compiler and function __gcd(a, b) doesn't give any error but, when I change it to gcd(a, b) in the same ide, it does give error that this function definition is not found.

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

When I run the same code in my local machine, everything happens in just the opposite way. __gcd(a, b) doesn't work while gcd(a, b) works.

推荐答案

不要使用bit/C++.h,它是私有头文件.

Don't use bit/C++.h, it's a private header.

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

Use proper C++ functions: 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.

相关文章