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

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

基本上,下面的代码将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,以下是对,它给出了一个段错误。我通过调试器尝试 运行 它,它说, EXC_BAD_ACCESS (code=1,address=0x101800004) 在代码中标记为 (Here) 的行。我做错了什么?

这是输入文件的 link:https://www.dropbox.com/s/79ygx4qo5qc8tsl/input.txt?dl=0

你比较这两个对的函数有问题。如果其中两对具有相同的 absort 将永远不会完成。

改为:

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;
    }
};