【发布时间】:2014-02-28 07:33:37
【问题描述】:
试图让它工作.. GDB 似乎表明索引可能由于某种原因而关闭。我正在使用一个名为 Record 的子类的向量,该向量主要包含人口(int)和名称(字符串),需要以两种方式进行排序。 bt 在第 27 行表示空指针,它是 isSmaller() 函数中的“if”语句。此函数与同一程序中的插入排序代码完美配合,但不是合并排序,所以我想知道合并排序代码有什么问题。请指教。算法有问题吗?
bt 返回以下内容:
#0 0x0000000000403160 in CensusData::isSmaller (this=0x7fffffffdd10, type=0, r1=0x609590, r2=0x0) at CensusDataSorts.cpp:27
#1 0x0000000000403510 in CensusData::mergeIt (this=0x7fffffffdd10, type=0, list=..., p=0, q=1, r=2) at CensusDataSorts.cpp:96
#2 0x0000000000403347 in CensusData::mergeSortIt (this=0x7fffffffdd10, type=0, list=..., p=0, r=2) at CensusDataSorts.cpp:70
#3 0x0000000000403645 in CensusData::mergeSort (this=0x7fffffffdd10, type=0) at CensusDataSorts.cpp:113
#4 0x0000000000401a50 in runMergeSorts (fp=...) at CensusSort.cpp:106
#5 0x0000000000401e6f in main (argc=2, argv=0x7fffffffe068) at CensusSort.cpp:174
代码出现在下面
bool CensusData::isSmaller(int type, Record* r1, Record* r2)
{
if(type==POPULATION)
{
if(r1->population <= r2->population)
return true;
}
else if(type==NAME)
{
if(*(r1->city) <= *(r2->city))
return true;
}
return false;
}
void CensusData::mergeSortIt(int type, vector<Record*>& list, int p, int r)
{
if(p < r)
{
int q = floor((p+r)/2);
mergeSortIt(type,list,p,q);
mergeSortIt(type,list,q+1,r);
mergeIt(type,list,p,q,r);
}
}
void CensusData::mergeIt(int type, vector<Record*>& list, int p, int q, int r)
{
int n1=q-p+1;
int n2=r-q;
int i,j;
vector<Record*> L(n1,0);
vector<Record*> R(n2,0);
for(i=0; i<n1; i++)
L[i]=list[p+i];
for(j=0; j<n2; j++)
R[j]=list[q+j+1];
i=0;
j=0;
for(int k=p; k<=r; k++)
{
if(isSmaller(type,L[i],R[j]))
{
list[k]=L[i];
i++;
}
else
{
list[k]=R[j];
j++;
}
}
}
void CensusData::mergeSort(int type)
{
mergeSortIt(type, data, 0, data.size()-1);
}
【问题讨论】:
-
既然您已经在 GDB 中调试,介意给我们函数调用回溯吗?请指出在显示的代码中发生崩溃的位置。还请添加所涉及的向量的大小以及崩溃发生时的索引。
-
您的意思是在 GDB 中输入 bt 并发布输出?程序收到信号 SIGSEGV,分段错误。 0x0000000000403160 in CensusData::isSmaller (this=0x7fffffffdd10, type=0, r1=0x609590, r2=0x0) at CensusDataSorts.cpp:27 27 if(r1->population population)
-
我在需要获取向量大小的地方使用 size() 函数,因为它们是从 csv 文件中填充的。附加了 OP。
-
是的,
bt命令的输出。请编辑您的问题以包含它。 -
解决此类问题的最佳方法是使用较小的数据集,然后逐行逐行执行代码,同时观察变量和索引。