解决UVA OJ上的分段错误

时间:2014-06-25 15:23:51

标签: c++ segmentation-fault runtime-error

下面是一个非常基本的代码,使用std::sort和自定义比较器函数对输入数据进行排序。

然而,比较器需要来自输入的值,该值不是数据的一部分,即下面的m变量。

当我针对在线评判运行代码时,我遇到了运行时错误 - 分段错误。

我想知道是什么导致这个问题,或者如何调试这个问题,因为我的想法已经用完了。提前谢谢。

问题是here

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int m;

bool cmp(int a, int b);

int main()
{
    int n, i;
    vector<int> num;
    int input;
    while(cin >> n >> m)
    {
        if(n == 0 && m == 0)        
        {
            cout << "0 0" << endl;
            break;
        }           
        for(i = 0; i < n; ++i)
        {
            cin >> input;
            num.push_back(input);
        }
        sort(num.begin(),num.end(),cmp);
        cout << n << " " << m << endl;
        for(i = 0; i < num.size(); ++i)
        {
            cout << num[i] << endl;
        }
        num.clear();        
    }
    return 0;
}

bool cmp(int a, int b)
{    
    if(a%m > b%m)
        return 0;
    else if(a%m < b%m)
        return 1;
    else  //a%m == b%m
    {
        if(a%2 == 0 && b%2 == 0)
        {
            if(a < b)
                return 1;
            else return 0;
        } 
        else if(a%2 == 0 && b%2 != 0)
        {
            return 0;
        }   
        else if(a%2 != 0 && b%2 == 0)
        {
            return 1;
        }
        else
        {
            if(a < b)
                return 0;
            else return 1;
        } 
    }    
}

1 个答案:

答案 0 :(得分:2)

您的cmp函数不符合严格弱排序的标准(http://en.wikipedia.org/wiki/Weak_ordering#Strict_weak_orderings)。非反射性标准(即cmp(x,x)必须评估为假)被违反。

对于任何奇数x cmp(x,x)将评估为真。您可能希望更改最里面的else子句中的两个return语句:

else {
    if(a < b) return true;
    else return false;
}

或更短:

else {
    return a < b;
}

在这种形式下,保证了无反思性。从目前为止我看到的其他标准也应该是有效的。

相关问题