void printTop5()
{
int counter = 1;
int x, y;
float civ;
cout << "Total no. of records available = " << pointVector.size();
cout << "Printing top 5 exploration destinations....";
sort(pointVector.begin(), pointVector.end(), ascendingCiv);
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
x = p1.getX();
y = p1.getY();
civ = p1.getCivIndex();
cout << counter << ")t";
if (civ > 0)
{
cout << "Civ idx: " << civ << " ; at sector(" << x << "," << y < ")n";
}
else
cout << "<No records available>";
}
}
bool ascendingCiv(const PointTwoD &d1, const PointTwoD &d2)
{
return d1.getCivIndex() > d2.getCivIndex();
}
当我运行这个函数时,我得到这个错误,它说分段故障核心被转储。知道吗?听说它有一些内存问题。
一个问题是你没有检查你的向量中是否真的至少有 5 个元素:
for (int i = 0; i < 5; i++)
{
PointTwoD p1 = pointVector[i];
如果i
超出向量的范围,则访问pointVector[i]
将调用未定义的行为。
循环条件可以更改为以下内容:
#include <algorithm>
//...
size_t loopEnd = std::min(pointVector.size(), 5);
for (size_t i = 0; i < loopEnd; i++)
{
PointTwoD p1 = pointVector[i];
循环将达到向量的大小或 5 个元素,以较小者为准。