【问题标题】:Strict weak ordering operator in C++C ++中的严格弱排序运算符
【发布时间】:2015-11-05 14:47:37
【问题描述】:

我正在为 TPS 编写遗传算法。我有从 std::vector 派生的类 Chromosome 并且具有成员资格。我想对染色体群进行排序。 IMO 我的 operator

bool Chromosome::operator<(const Chromosome & rhs) const
{
    const Chromosome& lhs = *this;
    if (lhs.fitness < rhs.fitness)
        return true;
    else
    {

        unsigned int size = lhs.size();
        unsigned int zeroCityIndexlhs = std::find(lhs.begin(), lhs.end(), 0) - lhs.begin();
        unsigned int zeroCityIndexrhs = std::find(rhs.begin(), rhs.end(), 0) - rhs.begin();
        for (unsigned int i = 1; i < size; i++)
        {
            if (lhs[(zeroCityIndexlhs + i) % size] < rhs[(zeroCityIndexrhs + i) % size])
                return true;
            else if (lhs[(zeroCityIndexlhs + i) % size] == rhs[(zeroCityIndexrhs + i) % size])
                continue;
            else
                return false;
        }
        return false;
    }
}

染色体 A 小于染色体 B,当它具有较小的适应度或相同的适应度并且从城市 0 开始的道路在字典上小于 B 中的道路时。程序编译但在排序时(使用 std::sort ()),运行时错误显示为“调试断言失败!...无效比较器”。

【问题讨论】:

  • 如果你拿了两条特定的染色体,assert failed operator&lt;(a, b) == operator&lt;(b, a) 呢?
  • std::vector 是什么?换句话说,您确定包含的对象上的operator&lt; 是正确的。
  • 顺便说一句,当您有退货声明时,您不需要else

标签: c++


【解决方案1】:

你错过了健身检查的另一面:

bool Chromosome::operator<(const Chromosome & rhs) const
{
    const Chromosome& lhs = *this;
    if (lhs.fitness < rhs.fitness)
        return true;
    else if (rhs.fitness < lhs.fitness)
        return false; // <== this!

否则,如果lhs.fitness &gt; rhs.fitness,您正在检查向量,而您不应该这样做。

【讨论】:

  • 它有效,非常感谢!似乎有时我不得不从编码中休息一下
【解决方案2】:

使用std::tuple:

bool Chromosome::operator<(const Chromosome & rhs) const
{
    // Fill in the ... here.
    using base_type = std::vector<...>;

    return std::tie(fitness, static_cast<base_type const&>(*this)) <
        std::tie(rhs.fitness, static_cast<base_type const&>(rhs));
}

旁注:从std::vector&lt;...&gt; 继承是非常可怕的。使用std::vector&lt;...&gt; 数据成员并将您需要的功能实现为转发函数。

【讨论】:

    【解决方案3】:

    rhs.size()&lt;lhs.size() 你的比较函数看起来严重错误。 (不仅是一个糟糕的比较规则,还有未定义的行为)。

    这可能会在您的operator[] 中修复,我看不到。所以我不能确定上述情况。但既然这符合所描述的症状,我假设你实际上并没有在operator[] 中修复它

    即使对于rhs.size()&gt;lhs.size(),您的代码中也存在一些非常可疑的地方。因此,您似乎假设它们的大小相同。如果是这样,请输入 assert,以便代码审查者相信这一点。

    【讨论】:

    • 是的,我认为它们的大小相同。我会在那里抛出断言。
    猜你喜欢
    • 2010-11-02
    • 2020-02-18
    • 2015-09-20
    • 2013-02-14
    • 2010-11-20
    • 2016-02-04
    • 1970-01-01
    • 2019-06-09
    • 1970-01-01
    相关资源
    最近更新 更多