sort function C++ segmentation fault(排序函数 C++ 分段错误)
问题描述
在这段代码中,对于向量大小,n >=32767,它给出了分段错误,但到 32766,它运行良好.可能是什么错误?这是完整的代码.
In this code, for vector size, n >=32767, it gives segmentation fault, but upto 32766, it runs fine. What could be the error? This is full code.
#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
",(int)p.max_size()); // prints 536870911**
    sort(p.begin(),p.begin()+n,compare);
    //for(int i=0;i<n;i++)
        //printf("%d %d
",p[i].first,p[i].second);
        printf("%.6f
",(p[n-1].second+p[n-2].second)/(20.0+p[n-1].first+p[n-2].first));
    return 0;
}
推荐答案
在 C++ 中,您的 compare 谓词必须是 严格弱排序.特别是 compare(X,X)必须返回false";对于任何 X.在您的比较函数中,如果两对相同,您点击测试 (p1.first <= p2.first) 并返回 true.因此,这个 compare 谓词没有强加严格的弱排序,传递给 sort 的结果是不确定的.
In C++, your compare predicate must be a strict weak ordering.  In particular, compare(X,X)
must return "false" for any X.  In your compare function, if both pairs are identical, you hit the test (p1.first <= p2.first) , and return true.  Therefore, this compare predicate does not impose a strict weak ordering, and the result of passing it to sort is undefined.
这篇关于排序函数 C++ 分段错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:排序函数 C++ 分段错误
 
				
         
 
            
        - 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 静态初始化顺序失败 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- STL 中有 dereference_iterator 吗? 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 从python回调到c++的选项 2022-11-16
- C++ 协变模板 2021-01-01
 
						 
						 
						 
						 
						 
				 
				 
				 
				