【问题标题】:Why __gcd() is throwing error in macOS mojave?为什么 __gcd() 在 macOS mojave 中抛出错误?
【发布时间】:2019-03-25 03:52:26
【问题描述】:
#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 失败

注意:在此处请求的函数模板特化 '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链接是ONLINE IDE

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

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

【问题讨论】:

  • __gcd 是私有的,不要使用它...错误信息中有什么不清楚的地方?它仅适用于无符号类型。
  • 您使用的是哪个编译器? g++ 还是 clang++?
  • @vivek:这很不幸。仍然没有借口使用实现私有函数
  • @vivek:实现私有部分指的是 __gcd。双下划线表示实现内部使用的非标准函数。标题是另一个问题

标签: c++ macos gcc g++ clang++


【解决方案1】:

不要使用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

【讨论】:

  • 这不能回答问题。
  • 此外,该函数仅来自 c++17。
  • 在 Mojave 上可用。
  • 此代码在使用 g++ 5.4.0 的 code.hackerearth.com 在线编译器上正常工作
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:
    int gcd(int a, int b){
        if (b == 0)
           return a;
        return gcd(b, a % b); 
    }
    

    在我的 mac 中,'__gcd()' 也无法正常工作并显示“使用未声明的标识符”,因此我必须预定义此函数。

    【讨论】:

      猜你喜欢
      • 2019-07-11
      • 2019-09-21
      • 2022-12-31
      • 2020-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-16
      • 2021-12-20
      相关资源
      最近更新 更多