【问题标题】:Custom Comparator based on two properties of an object throws exception基于对象的两个属性的自定义比较器抛出异常
【发布时间】:2017-07-23 20:47:39
【问题描述】:

我有一个 Business 对象列表,其中包含属性 id 和 rating,我想对它们进行排序,以便首先出现具有更高等级的对象,但是如果等级相同,则应保留原始顺序。

下面的代码是实现:

class Business {
public:
    int id;
    int rating;
    Business(int idP, int ratingP) :id(idP), rating(ratingP) {}
};
bool compare(Business b1, Business b2) {
    if (b1.rating != b2.rating) return b1.rating > b2.rating;
    return true;
}
void sortBusinessObjects(vector<Business>& v) {
    sort(v.begin(), v.end(), compare);
}

但是,当我测试它时,它抛出了异常(我正在使用 Visual Studio Express 并且看不到异常详细信息)

vector<Business> v{ {1, 3},{2, 5}, {9, 4}, {4, 3}, {5, 4} };
sortBusinessObjects(v);

我在这里猜测自定义比较器在导致问题的排序中返回的对象的结果相互矛盾?任何帮助表示赞赏。

【问题讨论】:

  • 什么异常?
  • 对不起,我使用的是 Visual Studio Express,它没有显示异常详细信息。但是,我认为逻辑非常简单,我认为我可能缺少一些关于 C++ 排序机制的东西
  • 查看输出窗口。它告诉你Expression: invalid comparator
  • 我看不出有任何理由在 sortBusinessObjects 中引用向量 (vector&lt;Business&gt; &amp;)。
  • @AndreasH。这是问题吗?我的输出窗口只显示 *.exe 已触发断点

标签: c++ vector comparator


【解决方案1】:

您必须编写一个有效的比较器。看看http://fusharblog.com/3-ways-to-define-comparison-functions-in-cpp/

设 f(x, y) 为比较函数。 f 是严格弱序 if 它满足三个不变量:

Irreflexivity
   f(x, x) = false.
Antisymmetry
   If x!=y and f(x, y) then !f(y, x)
Transitivity
   If f(x, y) and f(y, z) then f(x, z).
Transitivity of Equivalence
   Let equal(x, y) = !f(x, y) && !f(y, x). If equal(x, y) and equal(y, z) then equal(x, z).
bool compare(Business b1, Business b2)
{
    return b1.rating > b2.rating;
}

你必须使用std::stable_sort,它保留相等元素的顺序(!f(x,y) &amp;&amp; !f(y,x) 和 f 是比较函数的元素)

void sortBusinessObjects(vector<Business>& v)
{
    stable_sort(v.begin(), v.end(), compare);
}

输入

  • id=1,等级=3
  • id=2,等级=5
  • id=9,等级=4
  • id=4,等级=3
  • id=5,等级=4

创建输出

  • id=2,等级=5
  • id=9,等级=4
  • id=5,等级=4
  • id=1,等级=3
  • id=4,等级=3

我更喜欢 Lambda 表达式而不是全局比较器,因为这样您的所有代码都将在一个单一的、可读的函数中结束。

void sortBusinessObjects(vector<Business>& v)
{
    stable_sort(v.begin(), v.end(), [](auto b1, auto b2) {
        return b1.rating > b2.rating;
    });
}

【讨论】:

  • 我认为你搞砸了报告的输出:id=9rating=3 没有输入。您还应该解释(在问题中,而不是评论)stable_sort() 是什么以及为什么需要在这里。
  • 对不起。必须输入这个(没有复制/粘贴),确实输出搞砸了。会解决这个问题...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 2010-10-31
  • 2016-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多