sort函数C ++分段错误

问题描述 投票:12回答:3

在这段代码中,对于矢量大小,n> = 32767,它给出了分段错误,但是高达32766,运行正常。可能是什么错误?这是完整的代码。

#include<cstdio>
#include<cstring>
#include<cmath>
#include<queue>
#include<utility>
#include<algorithm>
#include<sys/time.h>
using namespace std;
#define MAX 100000

bool compare(pair<int,int> p1,pair<int,int> p2) {
    if(p1.second < p2.second)
        return 1;
    else if(p1.second > p2.second)
        return 0;
    if(p1.first <= p2.first)
        return 1;
    else
        return 0;
}

int main() {
    freopen("randomin.txt","r",stdin);
    int n;
    scanf("%d",&n);
    vector< pair<int,int> > p(n);
    for(int i=0;i<n;i++)
        scanf("%d%d",&p[i].first,&p[i].second);
    **printf("%d\n",(int)p.max_size()); // prints 536870911**
    sort(p.begin(),p.begin()+n,compare);

    //for(int i=0;i<n;i++)
        //printf("%d %d\n",p[i].first,p[i].second);
        printf("%.6f\n",(p[n-1].second+p[n-2].second)/(20.0+p[n-1].first+p[n-2].first));

    return 0;
}
c++ sorting segmentation-fault
3个回答
44
投票

这可能与您的分段错误无关,但......

在C ++中,您的“比较”谓词必须是strict weak ordering。特别是,对于任何X,“compare(X,X)”必须返回“false”。在比较函数中,如果两个对都相同,则按下测试(p1.first <= p2.first),并返回“true”。因此,这个“比较”谓词不会强加严格的弱排序,并且将其传递给“排序”的结果是不确定的。


3
投票

尝试使用n = 3276632770的所有值。我怀疑你会发现你正在经历某种溢出。这是因为2 ^ 15(32768)是可以使用16位表示的最大数字(假设您也允许负数)。您将不得不使用不同的数据类型。

建议:

得到它输出向量的maxsize:

cout << p.max_size();

让我们知道那是做什么的。一切正常,我预计它将在数亿(我的电脑上为536870911)。但如果它更像32768,那么这可能就是问题所在。


-2
投票

C ++有时很奇怪。我在basic_string.h文件中遇到了分段错误!我正在将我的代码库从GCC 4.2.1升级到GCC 5.4.0,突然发生了这个SEG FAULT,我想知道为什么相同的代码工作得更早,现在它在C ++内部破坏了STL。然后我抬起后面的痕迹,发现它是来自std::sort的指针向量,它使用自定义比较器来比较指针,基于通过成员函数ptr->GetName()获取对象的名称。这个GetName()正在返回一个字符串。

我花了一整天的时间来弄清楚basic_string文件中的更改可能导致这个错误。然后我开始了解这个“严格的弱排序”的事情,并相应地更改了我的比较器功能。仍然没有运气。

然后我调整了周围并将原始比较器功能更改为Functor。现在,它奏效了。我不确切地知道它背后的原因但它有效。

这是我原来的比较器功能:

bool swap (CLwPatternObj *a, CLwPatternObj *b){
    return a->GetName() < b->GetName() ) 
}

这是新的功能对象。

class CLwPatternComparator
{
public:
    bool operator() (CLwPatternObj *a, CLwPatternObj *b) 
    {
        return a->GetName() < b->GetName();
    }
};

相同的逻辑,但它适用于Function Object。

© www.soinside.com 2019 - 2024. All rights reserved.