这段代码中出现分段错误的可能原因是什么
What can be a possible reason for segmentation fault in this piece of code?
基本上,以下代码将n
对作为输入,每对都有两个部分,a
和b
。我使用自定义比较器对整个向量进行排序,该比较器将具有较高第二值(b)
的值放在第一位,如果b
相同,则将具有较高a
值的值放第二位。这是代码,
#include <iostream>
#include <utility>
#include <vector>
using namespace std;
struct mycomp
{
bool operator() (const pair<int,int> &p1, const pair<int,int> &p2)
{
if (p1.second > p2.second) // Here
return true;
else if (p1.second == p2.second && p1.first >= p2.first)
return true;
else
return false;
}
};
int main (void)
{
int i,n,a,b,foo;
cin>>n;
i = n;
vector<pair<int,int> > myvec;
while ( i != 0 )
{
cin>>a>>b;
myvec.push_back(make_pair(a,b));
i--;
}
int val = 0;
sort(myvec.begin(),myvec.end(),mycomp());
val = val + myvec[0].first;
int k = myvec[0].second;
foo = 1;
while ( k!=0 && foo < n) // This part basically calculates the values which I have to print.
{
//k--;
val = val + myvec[foo].first;
k = k + myvec[foo].second;
k--;
foo++;
}
cout<<val<<"n";
return 0;
}
在执行此操作时,以100作为输入,以下为对,它会产生seg错误。我试着通过调试器运行它,它说,代码中标记(此处(的行上的EXC_BAD_ACCESS (code=1,address=0x101800004)
。我做错了什么?
以下是输入文件的链接:https://www.dropbox.com/s/79ygx4qo5qc8tsl/input.txt?dl=0
您比较这两对的函数有错误。如果两个对具有相同的a
和b
,则sort
将永远不会完成。
更改为:
struct mycomp
{
bool operator() (const pair<int,int> &p1, const pair<int,int> &p2)
{
if ( p1.second != p2.second )
return p1.second > p2.second;
else
return p1.first > p2.first;
}
};
相关文章:
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- C++中的"expected unqualified-id"错误是什么?
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 我的代码中针对 NQueens 问题的错误是什么?
- 这个代码中的错误是什么,每次都会给我分段错误
- 'note: 候選人: Volume& Volume::operator=(const Volume&)'.这个错误是什么?
- 此气泡排序代码中的错误是什么?
- 第9行的给定代码中的错误是什么?
- C++ - "Incomplete type not allowed"错误是什么意思,我该如何修复它?
- 这个错误是什么?似乎没有理由出现
- 这个编译器错误是什么意思 - "qualified-id in declaration before ‘=’ token" C++?
- 这个boost.python程序中的错误是什么?
- C 如果该代码中的错误是什么
- TMB教程中的此编译错误是什么?
- 此代码运算符超载中的错误是什么?
- 英特尔SGX错误:8207错误是什么意思是当我无法正确加载飞地时
- 这个奇怪的"/usr/bin/ld: cannot find -lXAW_LIBRARY-NOTFOUND"错误是什么意思?
- 该代码的主要错误是什么,用于确定n`天后日期
- 错误 LNK2019:未解析的外部符号"外部"C"此错误是什么?
- 这个C++代码中的错误是什么