解决UVA OJ的分割故障

Solving a Segmentation Fault on UVA OJ

本文关键字:分割 故障 OJ UVA 解决      更新时间:2023-10-16

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

比较器需要一个不属于数据的输入值,即下面的m变量。

当我运行代码对在线判断,我得到一个运行时错误-分割错误。

我想知道什么可能导致这个,或者如何调试这个,因为我已经没有想法了。提前谢谢。

问题在这里。

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

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

对于任意奇数x, cmp(x,x)的计算结果为真。您可能希望更改最内层else-子句中的两个返回语句:

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

或短:

else {
    return a < b;
}

在这种形式下,非自反性得到保证。根据我目前所看到的,其他标准也应该是有效的。