我的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;
}
答案 0 :(得分:5)
如果第一个参数比第二个参数(std::sort
少 ,则a < b
的比较函数应返回true,但是如果相等({{ {1}}(由于a <= b
)。这可能会破坏else return true;
的实现。