【问题标题】:This piece of code compiles on my PC, but not on a standard C++98 compiler on a competition server这段代码可以在我的 PC 上编译,但不能在竞赛服务器上的标准 C++98 编译器上编译
【发布时间】:2018-12-25 18:48:42
【问题描述】:

我的编译器没有任何错误,我得到了正确的结果。我也尝试过在线 C++98 编译器,它也可以在那里工作。但是当我在比赛服务器上检查程序时,它说编译失败。

谁能告诉我如何处理我的编译器或我的代码有什么问题?这是程序:

#include <stdio.h>
#include <algorithm>

using namespace std;

class P
{
    public:
        int t;
        int l;
        P();
        P(int t, int l);
        bool operator<(P next);
};

P::P()
{
    this->t = 0;
    this->l = 0;
}

P::P(int x, int y)
{
    this->t = x;
    this->l = y;
}

bool P::operator<(P next)
{
    return this->l > next.l;
}

P a[110];

int main()
{
    int z, n, x, y, tim = 0;
    scanf("%d %d",&z,&n);

    for(int i = 0; i < z; i++)
    {
        scanf("%d %d",&x,&y);
        P b(x,y);
        a[i] = b;
    }   

    sort(a,a + z);
    tim = max(a[0].l,a[0].t);

    for(int i = 1; i <= z; i++)
    {
        tim += a[i - 1].l - a[i].l;
        tim = max(a[i].t,tim);
    }

    printf("%d\n",tim);
}

【问题讨论】:

  • 您是否从服务器收到任何错误消息?
  • 试试stdio.h -> cstdio。一个符合 c++98 的编译器不需要提供stdio.h,但大多数仍然提供。
  • bool operator&lt;(const P&amp; next) const;?
  • 与您的问题无关,但您可能应该为您的数组访问添加一些边界检查(z 的值)。另请注意,您将访问索引z 处的数组,该数组将被初始化为零(因为a 是一个全局变量,如果它是本地的a[z] 将是indeterminate)。跨度>
  • 谢谢@MatthieuBrucher!它是'bool operator

标签: c++ c++98


【解决方案1】:

std::max 接受两个 const T&amp; 参数。不声明比较运算符const:

bool operator<(const P& next) const;

std::max 的操作数没有匹配的运算符。

为什么这在你的本地机器上有效的一个解释是你对max的定义不是模板函数,而是一个宏,它不会有这个问题(但不会是标准的C++)。

【讨论】:

  • 现在 OP 是如何设法让它在其他任何地方构建的?这是一个真正的谜。
  • 是的,那是另一个谜。那么如果他使用VS,可能max实际上是宏,不会有这个“问题”。
  • 确实如此。所以奥秘在于 OP 到底是如何找到这么多提供 VS 的在线服务的:D
  • 公平地说,旧版本的 VS,新版本非常擅长符合标准。
【解决方案2】:

您的operator&lt; 应该是bool operator&lt;(const P &amp;next) const

【讨论】:

  • @Yksisarvinen 参数的副本不是问题(只是不必要的),但是由于排序函数当时的工作方式,函数不是 const 可能会导致编译错误。一些比较的东西可以期望参数是 const,你不能用 const 对象调用非 const 成员函数。
  • @Yksisarvinen 看到我的回答。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-10-17
  • 1970-01-01
  • 2013-09-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多