我正在为 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/