【问题标题】:Getting error when I change variable data type from "int" to "long" in CPP program当我在 CPP 程序中将变量数据类型从“int”更改为“long”时出现错误
【发布时间】:2021-07-24 02:03:04
【问题描述】:

我为这个问题编写了一个解决方案:在 codeforces 上的 Kefka and Company。 问题链接:https://codeforces.com/problemset/problem/580/B

我已经制作了一个成对的向量。我使用 for 循环遍历每一对向量。我考虑了该对的第一个元素并运行了 upper_bound 函数。然后我添加从当前索引到由upper_bound 提供的索引的对中的所有第二个元素。然后我将答案变量与当前总和进行比较并更新答案变量。

代码:

#include<bits/stdc++.h>
using namespace std;

int main(){
    long n,d,m,s;
    cin>>n>>d;
    vector< pair<long ,long> > v;
    for(long i=0;i<n;i++){
        cin>>m>>s;
        v.push_back( {m,s} );
    }
    sort(v.begin(),v.end());

    long ans=0;
    for(long i=0;i<n;i++){
        long j = upper_bound(v.begin(),v.end(), make_pair(v[i].first+d,INT_MIN) ) - v.begin();
        long x=0;
        long f=i;
        while(f<j){
            x+=v[f].second;
            f+=1;
        }
        ans=max(ans,x);
    }
    cout<<ans;
}

该代码工作正常,并为较小的测试用例提供了正确的结果,但它不能处理较大的测试用例。所以我将“int”数据类型更改为“long”,但我得到了这个错误以及许多其他错误:

/usr/include/c++/6/bits/predefined_ops.h:72:22: error: no match for ‘operator<’ (operand types are ‘const std::pair’ and ‘std::pair’)

       { return __val < *__it; }


 

【问题讨论】:

  • 我尝试包含#include&lt;pair&gt;,但它给出了错误:#include&lt;pair&gt; ^compilation terminated.
  • 我的错误std::pair 定义在&lt;utility&gt; 中也缺少&lt;vector&gt;&lt;algorithm&gt;&lt;iostream&gt;
  • 这是代码:ideone.com/YTfvk9。我按照你说的做了修改。但仍然收到此错误。 /usr/include/c++/6/bits/predefined_ops.h:72:22: error: no match for ‘operator&lt;’ (operand types are ‘const std::pair’ and ‘std::pair’)
  • 您是否故意编辑错误消息?您链接中的消息实际上报告了(operand types are ‘const std::pair&lt;long int, int&gt;’ and ‘std::pair&lt;long int, long int&gt;’)

标签: c++ vector binary-search


【解决方案1】:

仅当模板参数相同时才支持比较 std::pairs。

在您的代码中,make_pair(v[i].first+d,INT_MIN) 生成 std::pair&lt;long,int&gt; 类型。

你的意思可能是make_pair(v[i].first+d,LONG_MIN)

(See it compile successfully)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2017-06-20
    • 2021-03-26
    • 1970-01-01
    • 2019-05-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多