c++ - C++ 中的严格弱排序运算符

标签 c++

我正在为 TPS 编写遗传算法。我有类 Chromosome 派生自 std::vector 并且作为成员具有适应性。我想对染色体进行排序。 IMO my operator< 是“严格的弱排序”关系。但是,MVS 不这么认为。这是运算符的代码:

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 ()),运行时错误显示为“Debug Assertion Failed!... invalid comparator”。

最佳答案

您错过了健康检查的另一面:

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 > rhs.fitness,您会在不应该检查 vector 时检查 vector 。

关于c++ - C++ 中的严格弱排序运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33547566/

相关文章:

c++ - cin.getline() 没有将\0 添加到数组 C++ 的末尾

java - C#/Java如何存储二维数组,与C++有何不同?

c++ - Objective-C++ 中的复杂类层次结构

c++ - 使用分词器时出现 QUEX_PATH 问题

c++ - 编译器无法识别模板函数中的映射迭代器

C++ OpenMP : Split for loop in even chunks static and join data at the end

c++ - 在Allegro 5中使用多个计时器

c++ - 删除NULL但没有编译错误

c++ - 使用 enable_if 匹配数字作为函数参数

c++ - 通过 g++ 链接到外部静态库