我的Mac上的以下seg错误代码;但是,在Linux上工作正常(甚至没有valgrind错误)。
我怀疑比较功能给出的结果不一致;但是,我不知道如何。
(当有人指出时,我有种愚蠢的感觉:)
对于上下文:这是学生的代码。我知道有很多更好的编码方式,我只是为为什么错误而感到困惑。
using namespace std;
using Point = std::pair<double, double>;
using PointVector = vector<Point>;
extern PointVector cluster1;
bool sortComparison(const Point &point1, const Point &point2) {
if(point1.first < point2.first)
return true;
else if(point1.first > point2.first)
return false;
else if(point1.second < point2.second)
return true;
else if(point1.second > point2.second)
return false;
else
return true;
}
int main(int argc, char *argv[]) {
cout << "In" << endl;
std::sort(cluster1.begin(), cluster1.end(), sortComparison);
cout << "Out" << endl;
}
最佳答案
如果第一个参数的比第二个参数的少(std::sort
),则a < b
的比较函数应返回true,但是如果相等,则返回true(由于a <= b
,else return true;
)。这可能会破坏std::sort
的实现。
关于c++ - 这个比较是否不一致(还是存在另一个问题)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59252803/