此比较是否不一致(还是存在其他问题)?

时间:2019-12-09 16:18:38

标签: c++ sorting iterator comparator

我的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;

}

1 个答案:

答案 0 :(得分:5)

如果第一个参数比第二个参数(std::sort ,则a < b的比较函数应返回true,但是如果相等({{ {1}}(由于a <= b)。这可能会破坏else return true;的实现。