解决UVA OJ的分割故障
Solving a Segmentation Fault on UVA OJ
下面是一段非常基本的代码,使用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;
}
在这种形式下,非自反性得到保证。根据我目前所看到的,其他标准也应该是有效的。
相关文章:
- 分割故障C++矩阵
- C ,二进制树的高度,而不是检查我的子树是否为空,而是在检查我的子树是否是叶子节点.抛出分割故障
- 我正在为此代码分割故障
- 在执行strcpy时获取分割故障错误
- 空隙指针分割故障
- Xcode会产生分割故障,而不是例外
- OPENCV C 中的分割故障误差
- 分割故障:核心倾倒C 矢量对字符串:
- C 2D数组导致分割故障(核心倾倒)
- 分割故障/错误读数变量-C 列表
- DLSYM导致分割故障
- 使用C 中的操作员删除的分割故障
- 使用Linux X64下的Libmozjs-52(SpidermonKey)进行分割故障
- 使用长变量时分割故障(11)错误
- C - 返回字符串时的分割故障
- 创建VertexArray时的分割故障
- 向量分割故障的向量
- 从std :: fileSystem ::路径对象的类中退出时的分割故障
- C 矢量分割故障
- 基于向量的数据格式的分割故障误差