这段代码中出现分段错误的可能原因是什么

What can be a possible reason for segmentation fault in this piece of code?

本文关键字:错误 是什么 分段 段代码 代码      更新时间:2023-10-16

基本上,以下代码将n对作为输入,每对都有两个部分,ab。我使用自定义比较器对整个向量进行排序,该比较器将具有较高第二值(b)的值放在第一位,如果b相同,则将具有较高a值的值放第二位。这是代码,

#include <iostream>
#include <utility>
#include <vector>
using namespace std;
struct mycomp
{
    bool operator() (const pair<int,int> &p1, const pair<int,int> &p2)
    {
        if (p1.second > p2.second)  // Here 
            return true;
        else if (p1.second == p2.second && p1.first >= p2.first)
            return true;
        else
            return false;
    }
};
int main (void)
{
    int i,n,a,b,foo;
    cin>>n;
    i = n;
    vector<pair<int,int> > myvec;
    while ( i != 0 )
    {
        cin>>a>>b;
        myvec.push_back(make_pair(a,b));
        i--;
    }
    int val = 0;
    sort(myvec.begin(),myvec.end(),mycomp());
    val = val + myvec[0].first;
    int k = myvec[0].second;
    foo = 1;
    while ( k!=0 && foo < n)   // This part basically calculates the values which I have to print. 
    {
        //k--;
        val = val + myvec[foo].first;
        k = k + myvec[foo].second;
        k--;
        foo++;
    }
    cout<<val<<"n";
    return 0;
}

在执行此操作时,以100作为输入,以下为对,它会产生seg错误。我试着通过调试器运行它,它说,代码中标记(此处(的行上的EXC_BAD_ACCESS (code=1,address=0x101800004)。我做错了什么?

以下是输入文件的链接:https://www.dropbox.com/s/79ygx4qo5qc8tsl/input.txt?dl=0

您比较这两对的函数有错误。如果两个对具有相同的ab,则sort将永远不会完成。

更改为:

struct mycomp
{
    bool operator() (const pair<int,int> &p1, const pair<int,int> &p2)
    {
       if ( p1.second != p2.second )
          return p1.second > p2.second;
       else
          return p1.first > p2.first;
    }
};